I created it as a small story of Bash programming. This is the 6th bullet. This time it was quite tough.
For Bulls and Cows, see Wikipedia and here.
Originally a string guessing game, This time I will create it as a number guessing game.
#!/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 was fine, but I didn't use it because I don't trust it. Instead, I used the shuf command.
$ ./bulls_and_cows.sh
Welcome 'Bulls and Cows' Game
Please input digits of numbers => 3
./bulls_and_cows.sh:Line 39:warning: 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 !
The "Warning: command substitution: ignored null byte in input" message seems to come out when it contains null bytes. However, I'm ignoring it because it was difficult to generate N digits without using Null. Please comment if there is a good solution.
~~ I'm seriously trying to answer correctly. ~~
$ ./bulls_and_cows.sh
Welcome 'Bulls and Cows' Game
Please input digits of numbers => 3
./bulls_and_cows.sh:Line 39:warning: 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'
By creating this program
--Variables --Variable manipulation --Conditional expression --Repeating syntax --Function --read command --shuf command
I understand.
Recommended Posts