Je l'ai créé comme une petite histoire de programmation Bash. Ceci est la 6ème puce. Cette fois, c'était assez difficile.
Pour les taureaux et les vaches, voir Wikipedia et ici.
À l'origine un jeu de devinettes de chaînes de caractères, Cette fois, je vais le créer comme un jeu de devinettes.
#!/bin/bash
function chkAns {
bull=0
cow=0
num=$1
dig=$2
ans=$3
for i in $(seq 1 $dig)
do
for j in $(seq 1 $dig)
do
if [[ ${num:i:1} == ${ans:j:1} && $i == $j ]]
then
# echo bull: $bull #for debug
(( bull = bull + 1 ))
elif [[ ${num:i:1} == ${ans:j:1} && $i != $j ]]
then
# echo cow: $cow #for debug
(( cow = cow + 1 ))
fi
done
done
if (( bull == dig ))
then
echo -e "$dig bulls ! You did it !"
exit
else
echo -e "$bull bull and $cow cow."
fi
}
echo "Welcome 'Bulls and Cows' Game"
echo -e "Please input digits of numbers => \c"
read digits
tmp=$(shuf -i 0-9 -n $digits -z)
answer=${tmp:0:3}
#echo $answer #for debug
for k in $(seq 1 10)
do
echo -e "Input $digits numbers of your answer. (${k} time) => \c"
read num
chkAns $num $digits $answer
if (( $k == 10 ))
then
echo "You failed 10 times..."
fi
done
echo -e "The answer is '$answer'"
$ RANDOM était bien, mais je ne l'ai pas utilisé parce que je ne lui fais pas confiance. Au lieu de cela, j'ai utilisé la commande shuf.
$ ./bulls_and_cows.sh
Welcome 'Bulls and Cows' Game
Please input digits of numbers => 3
./bulls_and_cows.sh:Ligne 39:avertissement: command substitution: ignored null byte in input
Input 3 numbers of your answer. (1 time) => 321
2 bull and 0 cow.
Input 3 numbers of your answer. (2 time) => 324
2 bull and 0 cow.
Input 3 numbers of your answer. (3 time) => 325
3 bulls ! You did it !
Le message "Avertissement: substitution de commande: octet nul ignoré en entrée" semble apparaître lorsqu'un octet nul est inclus. Cependant, je l'ignore car il était difficile de générer N chiffres sans utiliser Null. Veuillez commenter s'il existe une bonne solution.
~~ J'essaye sérieusement de répondre correctement. ~~
$ ./bulls_and_cows.sh
Welcome 'Bulls and Cows' Game
Please input digits of numbers => 3
./bulls_and_cows.sh:Ligne 39:avertissement: command substitution: ignored null byte in input
Input 3 numbers of your answer. (1 time) => 345
1 bull and 0 cow.
Input 3 numbers of your answer. (2 time) => 219
1 bull and 0 cow.
Input 3 numbers of your answer. (3 time) => 398
1 bull and 0 cow.
Input 3 numbers of your answer. (4 time) => 470
1 bull and 1 cow.
Input 3 numbers of your answer. (5 time) => 709
1 bull and 0 cow.
Input 3 numbers of your answer. (6 time) => 507
2 bull and 0 cow.
Input 3 numbers of your answer. (7 time) => 504
1 bull and 0 cow.
Input 3 numbers of your answer. (8 time) => 570
1 bull and 1 cow.
Input 3 numbers of your answer. (9 time) => 407
2 bull and 0 cow.
Input 3 numbers of your answer. (10 time) => 307
2 bull and 0 cow.
You failed 10 times...
The answer is '567'
En créant ce programme
--Variable
Je comprends.