Loading...

FizzBuzz

The classic, if not tired, programming exercise based on the English kid's game. School children would sit in a circle, and starting from one, begin counting up. They would shout their number, if the number was a multiple of three, they would shout "Fizz" if it were a multiple of 5 they would shout "Buzz", if it were both a mulitple of 3 and 5 they would shout "FizzBuzz".

In one line

Albeit, very impressive...

Enumerable.Range(1, 100).Select( n => (n % 15 == 0) ? "FizzBuzz" : (
(n % 3 == 0) ? "Fizz" : (
(n % 5 == 0) ? "Buzz" : n.ToString()) ) ) .ToList() .ForEach(Console.WriteLine);

I have two issues this implementation. First, IEnumerable.Range does not support negative numbers and is limited by Int32 MaxValue (2,147,483,647). So you cannot go, say, from -100 to 100 and cannot itterate to 2,147,483,648.

Secondly, the hardcoding of the "multiple of" tests, seems like an opportunity lost.

In one line with an extension method

The is the implementation maintains the one-liner Linq but adds an extension method to overcome the Muliple Of test.

Enumerable.Range(1, 100).Select( n => (n.IsMultipleOf(15)) ? "FizzBuzz" : ( (n.IsMultipleOf(3)) ? "Fizz" : ( (n.IsMultipleOf(5)) ? "Buzz" : n.ToString()) ) ) .ToList() .ForEach(Console.WriteLine);

private static bool IsMultipleOf(this int sourceNumber, int targetNumber) { return (sourceNumber % targetNumber) == 0; }

My favorite

While this is not a one-liner, it overcomes my two initial issues.

It allows for any range (with minor edit) and extracates the Multiple Of test.

for (int i = -100; i <= 100; i++) { string s = i.ToString(); if (i.IsMultipleOf(15)) { s += " FizzBuzz"; } else if (i.IsMultipleOf(3)) { s += " Fizz"; } else if (i.IsMultipleOf(5)) { s += " Buzz"; } Console.WriteLine(s); }

private static bool IsMultipleOf(this int sourceNumber, int targetNumber) { return (sourceNumber != 0) ? (sourceNumber % targetNumber) == 0 : false; }


Note the modification to the MultipleOf extension method to test for zero.

So what's the takeaway? Shorter is not always better, and if anything, one ought to be suspicious of one-liners. Kind of like an if without an else.