Monday, February 28, 2011

Fizzbuzz game

http://imranontech.com/2007/01/24/using-fizzbuzz-to-find-developers-who-grok-coding/#comment-10055

Article on trivial programming tasks to test basic programming skills.

This is both fun and intricate.  The comments are an interesting look at code geeks at play. Some of the solutions posted are cryptic/wrong/ugly and I would be embarrassed to put them into production code but I respect the urge to have fun with the problem and turn it into a competition. I think the ability to have fun and "play" in code requires both fluency and mastery. Getting it wrong just shows there is still things to learn, not that you should not be trying to play the game.

My "professional" solution would be:

//Solution 1
//Code to solve the FizzBuzz task
//This should print the number from 1 to 100 and replace any that are a multiple of 3 with the string "Fizz" and a multiple of 5 with the string "Buzz". Multiples of both 3 and 5 should be replaced with "FizzBuzz".
#include < iostream >

void FizzBuzz( )
{

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

            if( i % 5 == 0)
            std::cout << "Buzz";
        }
        else
        {
            std::cout << i;
        }

        std::cout << std::endl;
    }
}

void main( void )
{
    FizzBuzz();
}

Naturally I also wanted to play and see how clever I could get... but as there were some really ugly one liners already in the comments I took a different approach.

//Solution 2 or the fun with rules/code solution
#include < iostream >

void main( void)
{
    std::cout << "the numbers 1 to 100" << std::endl;
}

Endless entertainment....

No comments:

Post a Comment