shell实现FizzBuzzWhizz问题示例(拉勾网面试题)
试题: https://www.jinshuju.net/f/egql3d
语言: shell (bash)
运行方式:
sh num-game.sh 数字1 数字2 数字3
如果不想使用传递数字的方式, 可以修改 num-game.sh 第 9 行, 将
num=$*
改为
num='数字1 数字2 数字3'
然后直接运行 sh num-game.sh 即可
#!/bin/bash
## author : taxkiz
## email : taxkiz@gmail.com
export path='/bin:/sbin:/usr/bin:/usr/sbin'
## num='3 5 7'
num=$*
## 检查输入的数字个数是否为 3 个
function ct () {
[ $( echo $* | sed 's/ /\n/g' | wc -l ) != '3' ] && echo " please enter 3 number ! " && exit 1
}
ct $num
## 个位数列表
nt='1/2/3/4/5/6/7/8/9'
## 检查输入的数字是否为个位数
function ck () {
for num in $*
do
[ $num == '0' ] && echo "error number '$num'" && exit 2
echo $nt | grep "\b$num\b" > /dev/null 2>&1
[ $? != '0' ] && echo "$num is not a single digit" && exit 3
done
}
ck $num
## 判断是否有重复的数字
function sn () {
if [ $1 == $2 ] || [ $1 == $3 ] || [ $2 == $3 ]; then
echo "error! there have same number : '$*'"
exit 4
fi
}
sn $num
## 大喊一声
function go () {
a1=$1
a2=$2
a3=$3
t1=$(( $1 * $2 ))
t2=$(( $1 * $3 ))
t3=$(( $2 * $3 ))
ta=$(( $1 * $2 * $3 ))
for num in {1..100}
do
echo $num | grep $a1 > /dev/null 2>&1
[ $? == '0' ] && echo 'fizz' && continue
echo "scale=2; $num/$ta" | bc | grep 00 > /dev/null 2>&1
[ $? == '0' ] && echo 'fizzbuzzwhizz' && continue
echo "scale=2; $num/$t1" | bc | grep 00 > /dev/null 2>&1
[ $? == '0' ] && echo 'fizzbuzz' && continue
echo "scale=2; $num/$t2" | bc | grep 00 > /dev/null 2>&1
[ $? == '0' ] && echo 'buzzwhizz' && continue
echo "scale=2; $num/$t3" | bc | grep 00 > /dev/null 2>&1
[ $? == '0' ] && echo 'fizzwhizz' && continue
echo "scale=2; $num/$a1" | bc | grep 00 > /dev/null 2>&1
[ $? == '0' ] && echo 'fizz' && continue
echo "scale=2; $num/$a2" | bc | grep 00 > /dev/null 2>&1
[ $? == '0' ] && echo 'buzz' && continue
echo "scale=2; $num/$a3" | bc | grep 00 > /dev/null 2>&1
[ $? == '0' ] && echo 'whizz' && continue
echo $num
done
}
go $num