Skip to content

Instantly share code, notes, and snippets.

@jacyzon
Created November 19, 2013 20:37
Show Gist options
  • Save jacyzon/7552113 to your computer and use it in GitHub Desktop.
Save jacyzon/7552113 to your computer and use it in GitHub Desktop.
N-digit guess number game
#!/bin/bash
# Guess number~
# 2013/11/20 Jason YiZhang Chen
ANSWER=1288
LENGTH=$(expr length $ANSWER)
declare -i a
until [ "$a" == $LENGTH ]; do
a=0 && b=0 && list=""
while [ 1 ]; do
# Read user input
read -p "Hello what's your number?" num
if [[ $num =~ "^[0-9]{${LENGTH}}$" ]]; then
break
else
echo "Please entering ${LENGTH}-digit number!"
fi
done
# compare to the answer
for (( i = 0; i < LENGTH; i++ )); do
if [ ${num:$i:1} == ${ANSWER:i:1} ]; then
a=$((a+1))
else
list="$list $i"
fi
done
for i in $list; do
for j in $list; do
if [ ${num:$i:1} == ${ANSWER:j:1} ]; then
b=$((b+1))
break
fi
done
done
# Show hit
echo "${a}A${b}B"
done
echo "Right!"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment