PowerShell Diversion #5: Let’s Play FizzBuzz
Here’s a quick diversion to exercise your basic scripting skills:
FizzBuzz is a game often played by schoolchildren as a way to practice their metal arithmetic abilities (or as a game for drunken adults, if you listen to Wikipedia). The rules we will use are:
- Count from 1 to 100, displaying the numbers as you go, however ...
- Any number divisible by 3 should be replaced by the word “Fizz”
- Any number divisible by 5 should be replaced by the word “Buzz”
- Any number divisible by both 3 and 5 should be replaced by the word “FizzBuzz”
The first 20 “numbers” would then be:
1, 2, Fizz, 4, Buzz, Fizz, 7, 8, Fizz, Buzz, 11, Fizz, 13, 14, FizzBuzz, 16, 17, Fizz, 19, Buzz
This is a deceptively simple task that I sometimes include as a challenge in my PowerShell workshops. While I just use it as an unusual and fun way to learn about scripting (specifically looping and decision making), some recruiters actually use it as a screening tool when hiring developers!
Once you have your solution, modify it to count the number of “Fizz”, “Buzz” and “FizzBuzz” entries between 1 and 1000.
Have fun and get some hints here if you need them.