Friday, March 15, 2013
Fizz Buzz in Bash
Fizz Buzz is a programming question given at interviews. Despite its absurd easiness it eliminates a large number of candidates.
#!/bin/bash
for i in {1..100}; do
if [[ $(($i % 3)) -eq 0 && $(($i % 5)) -eq 0 ]]; then
echo "fizz-buzz"
elif [[ $(($i % 3)) -eq 0 ]]; then
echo "fizz"
elif [[ $(($i % 5)) -eq 0 ]]; then
echo "buzz"
else
echo $i
fi
done
But... This is more elegant
#!/bin/bash
for i in {1..100}; do
if [[ $(($i % 15)) -eq 0 ]]; then
echo "fizz-buzz"
elif [[ $(($i % 3)) -eq 0 ]]; then
echo "fizz"
elif [[ $(($i % 5)) -eq 0 ]]; then
echo "buzz"
else
echo $i
fi
done
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment