News


A friend and mentor of mine took me to lunch one afternoon and asked me, over a plate of wings (mmmmm), this question:
If you wrote a program to print out the numbers 1-100 on one line each, replacing every number divisible by 3 with the word "fizz", every number divisible by 5 with the word "buzz", and every number divisible by both 3 and 5 with the word "fizzbuzz", how would you do that?
I didn't answer his question during that lunch, but the question stuck with me. He told me that his group has a regular "coding challenge" when things are slow at work. I was immediately enthralled with that idea and put it into practice the next week where I work.

The goal of this challenge was to produce the lowest number of lines of IL (CIL, MSIL, whatever you want to call it). The reason IL was chosen as the benchmark is because no matter what .NET language the code is written in, it all goes down to IL. Execution time isn't as baseline as one might think because of the difference in levels of performance due to hardware.

I do not claim that this solution was the winner of the challenge or that it's even a good one. This is simply one of the solutions. In future posts I will attempt to present only the best solutions. This is just the introductory challenge, so I'm not as concerned with fleshing it out as much as I will in the future. As far as C# is concerned, ternary expressions won out over if-else.


int i = 1;
do
{
Console.WriteLine(i % 3 == 0 ? (i % 5 == 0 ? "fizzbuzz" : "fizz") : (i % 5 == 0 ? "buzz" : i.ToString()));
i++;
} while (i < 101);

posted @ Monday, October 01, 2007 7:50 AM |

Comments

No comments posted yet.
Post A Comment
Title:
Name:
Email:
Website:
Comment:
Verification: