computer science goes bonk / all posts / rss / about

fizzbuzz madness

FizzBuzz Cola

Whew it is hot outside.

You know a great way to cool off? An ice-cold bottle of FizzBuzz.

A FizzBuzz problem is an easy programming problem that can be used to screen potential candidates for a job before bringing them in for a full interview. The idea is that an alarming number of applicants don't really grok basic programming concepts, and you can avoid wasting everybody's time by starting with the bar low.

And I mean really low. The most well-known FizzBuzz problem goes something like this:

  • Print the numbers from 1 to 100.
  • If the number is divisible by 3, also print "Fizz".
  • If the number is divisible by 5, also print "Buzz".

In other words, you should see something like this:

1
2
3 Fizz
4
5 Buzz
6 Fizz
7
8
9 Fizz
10 Buzz
11
12 Fizz
13
14
15 FizzBuzz

...and so on. A good programmer should be able to bang a solution to this problem out in a few minutes.

#include <iostream>

int main() {
   for (int i = 1; i <= 100; ++i) {
      std::cout << i << " ";
      if (i % 3 == 0) std::cout << "Fizz";
      if (i % 5 == 0) std::cout << "Buzz";
      std::cout << std::endl;
   }
}

But FizzBuzz might pop up elsewhere, too. Over in the comments to one of Stephan Lavavej's awesome "Advanced STL" videos, STL challenges a commenter who doesn't understand template metaprogramming to write FizzBuzz without runtime loops or runtime conditionals.

#include <iostream>

template <size_t N>
void fizzBuzzHelper(const char*) {}

template <>
void fizzBuzzHelper<0>(const char *str) {
   std::cout << str;
}

template <size_t N>
void fizzBuzz() {     // general case for N > 0
  fizzBuzz<N-1>();
  std::cout << N << " ";
  fizzBuzzHelper<N % 3>("Fizz");
  fizzBuzzHelper<N % 5>("Buzz");
  std::cout << std::endl;
}

template <>
void fizzBuzz<0>() {}  // base case for N == 0

int main() {
   fizzBuzz<100>();
}

Ahh, metaprogramming with FizzBuzz. I feel cooler already.