FizzBuzz and I Feel a Little Smug

A few months ago, there was a kerfuffle in the programming blog world about a little problem called FizzBuzz. Every now and then someone posts about their experiences interviewing candidates for coding positions. One such post was an example of a way to weed out the terrible developers from the merely not-that-good (i.e., the rest of us). It was titled Using FizzBuzz to Find Developers who Grok Coding and presented the following problem:

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”.

One of the artifacts of the phrasing used to frame the problem is a tendency to leap to using the mod operator, at least amongst commentators of the post. I found this odd, as my first inclination was something simpler, though less terse:


fizz = 3; buzz = 5
1.upto 100 do |i| unless i fizz or i buzz puts i next end Looking at the other solutions presented in the comments, of which there are many, in dozens of languages, I kind of remain attached to my simple, uncomplicated version. It looks a less flashy as it doesn't fit on a single line. On the other hand it probably is more efficient as it does little more than additions, comparisons and a loop. I also manage to avoid special-casing the FizzBuzz case---for multiples of 3 **and** 5---as it naturally falls out of the ordering of the if-statements. Perhaps it is just the rose-tinted spectacles of the creator, but I think that sometimes a little simple elegance trumps the swish-looking one-liner.
← Older
Using acts_as_sphinx with will_paginate in Rails
→ Newer
Back in my Hands