Ich habe es als kleine Geschichte der Bash-Programmierung erstellt. Dies ist die 6. Kugel. Diesmal war es ziemlich hart.
Bullen und Kühe finden Sie unter Wikipedia und hier.
Ursprünglich ein Ratespiel für Zeichenketten, Dieses Mal werde ich es als Zahlen-Ratespiel erstellen.
#!/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 war in Ordnung, aber ich habe es nicht benutzt, weil ich ihm nicht vertraue. Stattdessen habe ich den Befehl shuf verwendet.
$ ./bulls_and_cows.sh
Welcome 'Bulls and Cows' Game
Please input digits of numbers => 3
./bulls_and_cows.sh:Zeile 39:Warnung: 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 !
Die Meldung "Warnung: Befehlsersetzung: Nullbyte bei Eingabe ignoriert" wird angezeigt, wenn ein Nullbyte enthalten ist. Ich ignoriere es jedoch, weil es schwierig war, N Ziffern ohne Null zu generieren. Bitte kommentieren Sie, ob es eine gute Lösung gibt.
~~ Ich versuche ernsthaft richtig zu antworten. ~~
$ ./bulls_and_cows.sh
Welcome 'Bulls and Cows' Game
Please input digits of numbers => 3
./bulls_and_cows.sh:Zeile 39:Warnung: 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'
Durch das Erstellen dieses Programms
--Variable
Ich verstehe.