Mare Infinitus Mare Infinitus - 3 months ago 23
C# Question

Writing FizzBuzz

Reading the coding horror, I just came across the FizzBuzz another time.

The original post is here: Coding Horror: Why Can't Programmers.. Program?

For those who do not know:
FizzBuzz is a quite popular childrens game. Counting from 1 to 100,
and every time a number is divisible by 3 calling "Fizz", every time
a number is divisible by 5 calling "Buzz" and every time a number
is divisible by 3 and 5, calling "FizzBuzz instead of the number

But this time, I just started to code it down. It was a job of a minute,
but there are several things that I do not like.

Here is my code

public void DoFizzBuzz()
{
var combinations = new Tuple<int, string>[]
{
new Tuple<int, string> (3, "Fizz"),
new Tuple<int, string> (5, "Buzz"),
};

for (int i = 1; i <= 100; ++i)
{
bool found = false;

foreach (var comb in combinations)
{
if (i % comb.Item1 == 0)
{
found = true;
Console.Write(comb.Item2);
}
}

if (!found)
{
Console.Write(i);
}

Console.Write(Environment.NewLine);
}
}


So my questions are:


  1. How to get rid of the bool found?

  2. Is there a better way of testing
    than the foreach?


Answer

I think what you're trying to accomplish is a generic solution to FizzBuzz, that will work for any number of number-word combinations.

You have a good start - I think I can answer your questions with this example:

public void DoFizzBuzz()
{
    var combinations = new List<Tuple<int, string>>
    { 
        new Tuple<int, string> (3, "Fizz"), 
        new Tuple<int, string> (5, "Buzz"), 
    };

    Func<int, int, bool> isMatch = (i, comb) => i % comb == 0;
    for (int i = 1; i <= 100; i++)
    {
        Console.Write(i);

        var matchingCombs = combinations.Where(c => isMatch(i, c.Item1)).ToList();
        if (matchingCombs.Any())
        {
            Console.Write(string.Join("", matchingCombs.Select(c => c.Item2)));
        }
        else
        {
            Console.Write(i);
        }
        Console.Write(Environment.NewLine);
    }
}

In practice, you would pass combinations in to the method, but I included it inside just to be concise.