Jeff Atwood of Coding Horror wrote a post back in 2007 lamenting the incompetence of applicants to programming jobs. He used “FizzBuzz” as an example of a problem that every programmer ought to be able to solve. The statement is simple:
Write a program that prints the numbers from 1 to 100. But for multiples of three print “Fizz” instead of the number and for the multiples of five print “Buzz”. For numbers which are multiples of both three and five print “FizzBuzz”.
Readers took this as a challenge, and posted their solutions in the comment section. Some of these solutions did not satisfy the requirements. I think most of those programmers could come up with workable solutions if they understood the spec.
Atwood’s follow-up post instructed the readers not to bother with FizzBuzz, since that wasn’t the point of the discussion, but I think publicly presenting solutions to simple problems like this will help me get a job when I finally need one.
As such, I present my FizzBuzz solution in PHP. This isn’t optimized at all, in part because the goal of the exercise is to show the interviewer (or reader) how I think.
for ($i = 1; $i <= 100; $i++)
$printed = false;
if($i % 3 == 0)
$printed = true;
if($i % 5 == 0)
$printed = true;
In plan English:
- Repeat the following steps for the integers from 1 to 100, inclusive.
- If the integer is a multiple of 3, write “Fizz,” and make a note of the fact that you wrote something.
- If the integer is a multiple of 5, write “Buzz,” and make a note of the fact that you wrote something.
- If you didn’t already write something for this integer, write the integer itself.
- Write the next thing on a new line.
Some other correct solutions treat multiples of 15 as a special case, which allows them to use ‘else if’ and refrain from making a note of whether we’re supposed to write the integer. That’s probably no less robust, but my immediate instinct upon reading the problem statement is what I wrote above.