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

Linq me a FizzBuzz

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

Problem

I got this requirement recently:

Write some code that prints out the following for a contiguous range of numbers:

  • the number 'fizz' for numbers that are multiples of 3



  • 'buzz' for numbers that are multiples of 5



  • 'fizzbuzz' for numbers that are multiples of 15



e.g. if I run the program over a range from 1-20 I should get the following output

1 2 fizz 4 buzz fizz 7 8 fizz buzz 11 fizz 13 14 fizzbuzz 16 17 fizz 19 buzz


This attempt was done this way because I needed to print the sequence on the console and I needed to show the corresponding tests ala TDD.

public static class Evaluate
{
    public static string FizzBuzz(int start, int end)
    {
        return Enumerable.Range(start, (end - start) + 1)
            .Select(FizzOrBuzz)
            .Aggregate(String.Empty, (y, x) => String.Format("{0} {1}", y, x))
            .Trim();
    }

    public static string FizzOrBuzz(int n)
    {
        if (n % 15 == 0) return "fizzbuzz";
        if (n % 3 == 0) return "fizz";
        if (n % 5 == 0) return "buzz";
        return n.ToString();
    }
}

Solution

I'd prefer to use the String.Join method instead of the Aggregate:

public static string FizzBuzz(int start, int end)
{
    return String.Join(" ", Enumerable.Range(start, end - start + 1).Select(FizzOrBuzz));
}


This should eliminate multiple string concatenations.

EDIT. Removed the superfluous generic type parameters.

Code Snippets

public static string FizzBuzz(int start, int end)
{
    return String.Join(" ", Enumerable.Range(start, end - start + 1).Select(FizzOrBuzz));
}

Context

StackExchange Code Review Q#77401, answer score: 18

Revisions (0)

No revisions yet.