Fizz Buzz. A “classic” programming interview question.
The Question
Given all the numbers 1 through 100:
- If the number is a multiple of 3, print “Fizz” to the screen
- If the number is a multiple of 5, print “Buzz” to the screen
- If neither of the above is true, print the number to the screen
It is important to realize that there are a few special cases:
- What happens when the number is a multiple of 3 and 5?
- What would happenĀ if you include 0 on the list?
The Answer
The implementation I wrote which I like the best is as follows.
Iterate from 1 to 100, then for each number, check for multiples using if test statements. Note that the statements cannot be nested, else for multiples of both 3 and 5, the statement will exit after the first statement is true.
#!/bin/bash
#set -xv
for i in {1..100}
do
if [[ $(( $i % 3 )) == 0 ]]; then echo "Fizz"; fi
if [[ $(( $i % 5 )) == 0 ]]; then echo "Buzz"; fi
if [[ $(( $i % 3 )) != 0 && $(( $i % 5)) != 0 ]]; then echo "$i"; fi
done
Running the script is the same as running any script. First, make the file executable
chmod +x fizz_buzz
Second, run it.
./fizz_buzz
The output should look like this (only the first 20 entries shown)
1 2 Fizz 4 Buzz Fizz 7 8 Fizz Buzz 11 Fizz 13 14 Fizz Buzz 16 17 Fizz 19 Buzz
In anĀ alternate version, at the start of the for-do-loop, you can use a “3rd-party” variable which eliminates the need for the huge test in the 3rd if statement.
#!/bin/bash
#set -xv
for i in {1..100}
do
var=""
if [[ $(( $i % 3 )) == 0 ]]; then var="Fizz" && echo "$var"; fi
if [[ $(( $i % 5 )) == 0 ]]; then var="Buzz" && echo "$var"; fi
if [[ "$var" == "" ]]; then echo "$i"; fi
done
Finally, using a case statement, which is very ugly since you have to correctly handle when the number is a multiple of 3 and 5.
#!/bin/bash
#set -xv
for i in {1..100}
do
var=$(( $i % 3 ))
case $var in
0) echo "Fizz"
var2=$(( $i % 5))
case $var2 in
0) echo "Buzz";;
*) ;;
esac;;
*) var2=$(( $i % 5))
case $var2 in
0) echo "Buzz";;
*) echo "$i";;
esac
esac
done