HiveBrain v1.2.0
Get Started
← Back to all entries
patterncsharpModerate

Writing FizzBuzz

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
writingfizzbuzzstackoverflow

Problem

First of all, I came up with that question on SO already. But I am offered different solution which are "better" in some ways. The goal is to improve this specific version, not to create another one.

Here is what it is about:

Reading Coding Horror, I just came across the FizzBuzz another time. The original post is here.

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

public void DoFizzBuzz()
{
    var combinations = new Tuple[] 
    { 
        new Tuple (3, "Fizz"), 
        new Tuple (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:

  • How to get rid of the bool found?



  • Is there a better way of testing than the foreach?

Solution

I think if you're going to set up a set of data to iterate over you should start thinking more functionally. Why not use an array of functions and aggregate over them instead? That puts the logic in the functions, not in the function that utilises the data.

For example:

static void Main(string[] args)
{
    var generators = new Func[]
    {
        (s, i) => i % 3 == 0 ? s + "Fizz" : s,
        (s, i) => i % 5 == 0 ? s + "Buzz" : s,
        (s, i) => s ?? i.ToString()
    };
    var results = Enumerable.Range(0, 100).Select(i => generators.Aggregate((string)null, (s, f) => f(s, i))).ToList();
    results.ForEach(Console.WriteLine);
}

Code Snippets

static void Main(string[] args)
{
    var generators = new Func<string, int, string>[]
    {
        (s, i) => i % 3 == 0 ? s + "Fizz" : s,
        (s, i) => i % 5 == 0 ? s + "Buzz" : s,
        (s, i) => s ?? i.ToString()
    };
    var results = Enumerable.Range(0, 100).Select(i => generators.Aggregate((string)null, (s, f) => f(s, i))).ToList();
    results.ForEach(Console.WriteLine);
}

Context

StackExchange Code Review Q#14216, answer score: 11

Revisions (0)

No revisions yet.