Log et al – Peter Curd

An irreverent peek into the inner rumblings of Peter Curd

Jul

1

The FizzBuzz problem

By pcurd

Amy Kimber posted an article today referring to a post from Nick Telford on twitter:

Will The Real Programmers Please Stand Up? http://retwt.me/1NEBw // another example of how diluted our industry really is (link)

This interests me as I often find job interviews to be very generic and after about four in a row you get to know all the answers and appear much cleverer than you perhaps are.  I like a problem that makes you think and although FizzBuzz is a trivial problem, I wanted to answer it with a little bit of real world thinking.

To quote Amy, the FizzBuzz problem is “The idea is simple, all you have to do is write a program that prints out the numbers 1 to 100, but for multiples of 3, print Fizz instead of the number and for multiples of 5 print Buzz. If the number is a multiple of both, FizzBuzz should be printed.”

In the real world, specs change. Today it’s 3 and 5 and tomorrow it’s 4 and 9 and we need to add an extra one “Bibble” for 11.  I decided to solve the problem with a list of number and word pairs so that changing it would be easy.  .Net provides a nice KeyValuePair generic which I used as Int,String.

Originally I had this implemented using a Dictionary but as FizzBuzz must be implemented the correct way around (not BuzzFizz) I needed to change this to a SortedDictionary to ensure order of execution.

Code is as below:

using System;
using System.Collections.Generic;

namespace FizzBuzz
{
    class Program
    {
        static ICollection<KeyValuePair<int, string>> wordlist;
        static void Main(string[] args)
        {
            wordlist = new SortedDictionary<int, string>();
            wordlist.Add(new KeyValuePair<int, string>(3, "Fizz"));
            wordlist.Add(new KeyValuePair<int, string>(5, "Buzz"));
            PrintFizzBuzz(1, 100);
            Console.ReadKey();
        }

        static void PrintFizzBuzz(int start, int finish)
        {
            for (int i = start; i <= finish; i++)
            {
                Console.WriteLine(CalculateFizzBuzz(i));
            }
        }

        static object CalculateFizzBuzz(int i)
        {
            string CalculateFizzBuzz = "";
            foreach (KeyValuePair<int, string> word in wordlist)
            {
                if (i % word.Key == 0)
                    CalculateFizzBuzz += word.Value;
            }
            if (CalculateFizzBuzz.Length == 0)
                CalculateFizzBuzz = i.ToString();

            return CalculateFizzBuzz;
        }
    }
}

Update 27th February 2012:

Many great answers in the comments below, great to see how different languages can solve this problem. My solution is designed around flexibility and the ability to change the list of “Fizz”es and “Buzz”es which takes away from the brevity possible!

I found this article today from Calvin Bottoms regarding implementing FizzBuzz in Haskell – at 78 characters it’s impressive and his explanation of how it develops is a great read.

4 Responses so far

It’s a fascinating problem, so many different options.

I think anyone – i.e. you and me – who codes in enough slack that when the specs change – and change they will – should certainly get bonus marks.

The trick is to allow for slack WITHOUT making hte original solution unreadable or having too much overhead for the simple case.

My answer – a little shorter than the C# version, but then again Ruby’s a better language : http://fringley.wordpress.com/2010/08/27/a-little-late-on-the-fizz-buzz-problem/

[…] by The Fizz Buzz problem and diving in too soon and The Fizz Buzz Problem. Tags fizz buzz, ruby Categories […]

7 yrs later… C# can be shorter too. With type safety as bonus.

using static System.Console;
using System.Collections.Generic;
using System.Linq;
namespace FizzBuzzApp
{
class Program
{
static void Main(string[] args)
{
string fizzBuzz(int input)
{
var map = new Dictionary { { 3, “Fizz” }, { 5, “Buzz” } };
var value = map.Keys.Where(factor => input % factor == 0).Aggregate(“”, (current, factor) => current + map[factor]);
if (string.IsNullOrEmpty(value))
value = input.ToString();
return value;
}
Enumerable.Range(1, 100).Select(fizzBuzz).ToList().ForEach(WriteLine);
}
}
}

Leave a comment