torsdag 8 maj 2008

C# FizzBuzz :)

Here is my thoughts and solution to Gustafs Functional FizzBuzz problem! It's more or less a copy from what I wrote as a comment in his old blog, except for some modifications in the code snippet below.

I believe that in almost all cases, where you should write a solution for a given problem, you have two solutions to choose from. The first one focuses on writing well looking, readable, code (which is always good), the second focuses on writing fast code (which is required in some projects).

My solution for a bit faster code (I guess), would be this (c# style):

for (int i = 1, j = 1, k = 1; i <= 100; i++, j++, k++)
{
string t = "";
if (j == 3)
{
t = "Fizz";
j = 0;
}
if (k == 5)
{
t += "Buzz";
k = 0;
}
if (t == "")
{
t = i.ToString();
}
Console.WriteLine(t);
}

The difference is that you don't need to call "x `mod` m == 0" to find out if you should print Fizz or Buzz, instead two extra counters are used to keep track on when to write Fizz and when to write Buzz. I guess you could write this in functional style as well, but my haskell skills are a bit out of date so I wouldn't dare to try that ;)

1 kommentar:

RRave sa...

Dear Sir,

I have a launched new web site for .NET programming resources. www.codegain.com. I would like to invite to the codegain.com as author and supporter. I hope you will joins with us soon.

Thank You
RRaveen
Founder www.codegain.com