25

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 children's game. Counting from 1 to 100, and every time a number is divisible by 3 the string "Fizz" is called, every time a number is divisible by 5 the string "Buzz" is called and every time a number is divisible by 3 and 5 both strings together "FizzBuzz" are called instead of the number.

This time, I wrote the code and it took me 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 do I get rid of the bool found?
  2. Is there a better way of testing than the foreach?
9
  • 15
    Probably best for CodeReview: codereview.stackexchange.com Aug 1, 2012 at 17:47
  • Will have a look on that. I do not want other solutions, I want to improve "my" solution. Aug 1, 2012 at 17:54
  • What I definitly want is to stick to the outside declared pairs. And I am sure there is a way of getting rid of the bool. Aug 1, 2012 at 18:10
  • 3
    If you're going to all the trouble of declaring a list of acceptable matches (overkill really), then I wouldn't even declare the list inside of your method. Pass it in as a parameter and let the calling code decide what is in the list. Then you've totally abstracted that part away. Otherwise, you're not gaining any benefit from creating the list in the first place (code will still need to be changed in the method if you want to change the list).
    – Jason Down
    Aug 1, 2012 at 18:23
  • 1
    This is for shortness of the question. Eventually I should even pass in the borders 1 and 100. I just wanted to have a solution that gets rid of the inline magic and is concise. Aug 1, 2012 at 18:35

47 Answers 47

197

I think your implementation is unnecessarily complex. This one does the job and is easier to understand:

public void DoFizzBuzz()
{
    for (int i = 1; i <= 100; i++)
    {
        bool fizz = i % 3 == 0;
        bool buzz = i % 5 == 0;
        if (fizz && buzz)
            Console.WriteLine ("FizzBuzz");
        else if (fizz)
            Console.WriteLine ("Fizz");
        else if (buzz)
            Console.WriteLine ("Buzz");
        else
            Console.WriteLine (i);
    }
}
15
  • 7
    @MareInfinitus, your version also uses magic numbers and magic strings, they're just declared somewhere else... You should keep to the KISS principle ;) Aug 1, 2012 at 17:59
  • 10
    If they are declared in a proper place, there is no magic. And the number and string are tied together, just as they should, outside the code. Introducing another number / key pair is then a nonissue. It is just adding another number / key pair, no more, no magic. Aug 1, 2012 at 18:00
  • 9
    @MareInfinitus I really think you're missing the context of the original question. I agree with KISS in this case because the question establishes very few requirements. You should do only what is necessary to accomplish the task.
    – TheBuzzSaw
    Aug 1, 2012 at 18:12
  • 51
    This is the correct answer. Fizzbuzz isn't the place to complexify for the sake of making it supposedly cleaner. If someone feels the need to introduce complexity in FizzBuzz, I wouldn't let them touch production code.
    – Gilles
    Aug 6, 2012 at 19:08
  • 2
    @ema, uh? OCP is an OO principle; this program isn't even object oriented, how can it violate OCP? Jan 10, 2014 at 10:23
27

Unrolled for maximum efficiency. This program can outfizzbuzz all others.

public void FizzBuzz()
{
    const string FIZZ = "Fizz";
    const string BUZZ = "Buzz";
    const string FIZZBUZZ = "FizzBuzz";

    int i = 0;
    while (i < 150)
    {
        Console.WriteLine(++i);
        Console.WriteLine(++i);
        Console.WriteLine(FIZZ); ++i;
        Console.WriteLine(++i);
        Console.WriteLine(BUZZ); ++i;
        Console.WriteLine(FIZZ); ++i;
        Console.WriteLine(++i);
        Console.WriteLine(++i);
        Console.WriteLine(FIZZ); ++i;
        Console.WriteLine(BUZZ); ++i;
        Console.WriteLine(++i);
        Console.WriteLine(FIZZ); ++i;
        Console.WriteLine(++i);
        Console.WriteLine(++i);
        Console.WriteLine(FIZZBUZZ); ++i;
    }
}
5
  • 6
    HEAVY LAUGHING HERE! +1 (btw, I think C# compiler will optimize it already to unrolled version) Aug 1, 2012 at 18:14
  • 5
    Note that this one does not stop at 100.
    – Wug
    Aug 1, 2012 at 18:14
  • 1
    how should it, it has 15 unrolled events, it can not stop at 100. (as 100 is no multiple of 15) Aug 1, 2012 at 18:15
  • 1
    It stops at 150 since the loop increments i a total of 15 times each iteration.
    – Wug
    Aug 1, 2012 at 18:16
  • "maximum efficiency"? codegolf.stackexchange.com/a/236630 FizzBuzz outputting at 56GiB/s. Mar 8, 2022 at 5:38
26

Take advantage of conditional format specifiers to get a nicely golfed version:

public void DoFizzBuzz()
{
    for(int i=1;i<101;i++)Console.WriteLine("{0:#;}{1:;;Fizz}{2:;;Buzz}",i%3*i%5==0?0:i,i%3,i%5);
}
6
  • what the heck, this one is crazy! ... so +1 ;) Aug 1, 2012 at 18:04
  • 15
    Is this supposed to impress the interviewer? Even he will scratch his head. Easy to read and maintain code is important. Jan 28, 2015 at 19:05
  • 8
    Can be further golfed with string interpolation a few years later: $"{(i%3*i%5==0?0:i):#;}{i%3:;;Fizz}{i%5:;;Buzz}"
    – Bill Barry
    Mar 28, 2016 at 23:22
  • 1
    Can be further golfed by changing ==0 to <1, dropping the ; separator from the format (# never displays a zero that is not a significant digit), and using the newline character. System.Console.Write($"{(++i%3*i%5<1?0:i):#}{i%3:;;Fizz}{i%5:;;Buzz}\n");
    – lordcheeto
    Sep 28, 2016 at 2:39
  • 2
    @SageMage Code golf challenges for simple problems can give you a better understanding of the syntax.
    – lordcheeto
    Sep 28, 2016 at 2:43
22

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.

9
  • LINQ helps even here! I like that one! +1! Possible candidate for accept! Aug 1, 2012 at 18:11
  • 12
    It's one thing to "solve the FizzBuzz problem" excessively and thoroughly. It's another to think that this would somehow make you look good in an interview situation. It's a fun solution, but it is painfully complex given the original problem's description.
    – TheBuzzSaw
    Aug 1, 2012 at 18:14
  • 4
    Join combinations.Where(c=>isMatch(i,c.Item1)).Select(c=>c.Item2).DefaultIfEmpty(i.ToString()) and you won't even need the if statement Aug 1, 2012 at 18:18
  • In an interview situation, I would definitly do the simplest thing to solve the problem. But sitting relaxed in front of my computer, the first thing after that is a refactoring. Aug 1, 2012 at 18:20
  • 3
    @TheBuzzSaw I agree, I would never give this answer in an interview, but it's a fun one to think about. Now we just need to hook it into a database table holding the combo's, and set up a web service for transmitting the results..
    – Rob H
    Aug 1, 2012 at 18:20
21

3rd edit:

Here is one way to "get rid of the bool" from your version (that is replace the for loop in your original question with this):

for (int i = 1; i <= 100; i++)
{
  var x = combinations.Where(n => i % n.Item1 == 0);

  if (x.Count() == 0)
    Console.Write(i);
  else
    Console.Write(string.Join("",x.Select(e => e.Item2)));

  Console.Write(Environment.NewLine);
}

Prior answers:

For a pure C# solution check out Keith Thompson's solution.

using System;
class FizzBuzz {
    static void Main() {
        for (int n = 1; n <= 100; n ++) {
            if (n % 15 == 0) {
                Console.WriteLine("FizzBuzz");
            }
            else if (n % 3 == 0) {
                Console.WriteLine("Fizz");
            }
            else if (n % 5 == 0) {
                Console.WriteLine("Buzz");
            }
            else {
                Console.WriteLine(n);
            }
        }
    }
}

I worked a bit on FixBuzz using linq. These are the solutions I came up with -- I believe they represent the best way to express the solution to this problem using Linq. (GitHub)

using System;
using System.Linq;

class FizzBuzz {
  static void Main() {
    var list = Enumerable.Range(1,100)
                .Select(n => {
                      if (n % 15 == 0) {
                        return "FizzBuzz";
                      }
                      if (n % 3 == 0) {
                        return "Fizz";
                      }
                      if (n % 5 == 0) {
                        return "Buzz";
                      }
                      return n.ToString();
                    });

    foreach(string item in list)
      Console.WriteLine(item);
  }
}

and the crazy one line version:

using System;
using System.Linq;

class FizzBuzz {
    static void Main() {
      Console.WriteLine(
      String.Join(
        Environment.NewLine,
        Enumerable.Range(1, 100)
          .Select(n => n % 15 == 0 ? "FizzBuzz" 
                     : n % 3 == 0 ? "Fizz" 
                     : n % 5 == 0 ? "Buzz" 
                     : n.ToString())
      ));
    }
}
4
  • This is another solution, but does not answer my questions. Besides that, I did not do the -1! Aug 1, 2012 at 17:37
  • It gets rid of the bool found... it is another way (better is subjective).
    – Jason Down
    Aug 1, 2012 at 17:41
  • @KeithThompson - I hope you don't mind my quoting you in this answer.
    – Hogan
    Aug 1, 2012 at 17:49
  • @HenkHolterman - that is supposed to be a drop in to the for loop of the original question.
    – Hogan
    Aug 1, 2012 at 20:08
15
public void DoFizzBuzz()
{
    for (int i = 1; i <= 100; i++)
    {
        if (i % 3 == 0)
            Console.Write("Fizz");
        if (i % 5 == 0)
            Console.Write("Buzz");
        if (!(i % 3 == 0 || i % 5 == 0))
            Console.Write(i);

        Console.Write(Environment.NewLine);
    }
}

This gets rid of the bool found, but forces you to do duplicate evaluation. It is slightly different from some of the other answers using i % 15 == 0 for the FizzBuzz qualification. Whether or not this is better is up for debate. However, it is a different way.

2
  • 1
    It is a different way, and I want specifically to improve "my" way. Aug 1, 2012 at 18:03
  • 2
    I like the creative use of the newline to print "FizzBuzz"... clever! Feb 4, 2015 at 19:35
13

Did anyone do this one already?

Enumerable.Range(1, 100).Select(x =>
                (x % 15 == 0) ? "FIZZBUZZ"
                : (x % 5 == 0) ? "BUZZ"
                : (x % 3 == 0) ? "FIZZ"
                : x.ToString()
                )
                .ToList()
                .ForEach(console.WriteLine);
1
  • 1
    concise, and a nice solution Nov 28, 2013 at 6:47
10

I think you started with a complicated way. Improving that code would be more complicated. You can use a temp variable to track and display that variable at the end of the FizzBuzz check. Below is code and you can also watch this detail c# FizzBuzz youtube video ( http://www.youtube.com/watch?v=OX5TM3q-JQg ) which explains how the below code is implemented.

    for (int j = 1; j <= 100; j++)
    {
    string Output = "";

    if (j % 3 == 0) Output = "Fizz";// Divisible by 3 --> Fizz

    if (j % 5 == 0) Output += "Buzz"; // Divisible by 5 --> Buzz

    if (Output == "") Output = j.ToString(); // If none then --> number

    Console.WriteLine(Output); // Finally print the complete output
    }
1
  • 2
    The best solution so far :) Sep 11, 2014 at 10:02
9

Will add my 5 cents to solution by Linq. Everybody is using Select, which is basically Map function. IMHO foldl function suits better to solve this quiz:

Console.WriteLine(
                Enumerable
                .Range(1, 100)
                .Aggregate(new StringBuilder(), (builder, i)
                    => i % 15 == 0 ? builder.AppendLine("FizzBuzz")
                     : i % 3 == 0 ? builder.AppendLine("Fizz")
                     : i % 5 == 0 ? builder.AppendLine("Buzz")
                     : builder.AppendLine(i.ToString()))
                .ToString());
8

Linq:

Enumerable.Range(1, 100).ToList().ForEach(i => Console.WriteLine( i % 3 * i % 5 == 0 ? (i % 3 == 0 ? "Fizz" : "") + (i % 5 == 0 ? "Buzz" : "") : i.ToString()));
4

In my opinion, the FizzBuzz problem is always presented as a challenge to the interviwee to make the word FizzBuzz appear without explicitly printing it. Here is my solution in C#.

internal void PrintFizzBuzzAlternative(int num)
{
    if (num % 5 == 0)
        Console.Write("Fizz");
    if (num % 3 == 0)
        Console.Write("Buzz");
    if (num % 5 != 0 && num % 3 != 0)
        Console.Write(num);
    Console.WriteLine();
}
1
  • if, else if, else to remove the last two tests
    – sofsntp
    Jan 25, 2019 at 14:01
4

Not the most efficient, but here's one using C#-6 string interpolation:

void Main()
{
    for (int i = 1; i <= 100; i++)
    {
       Console.WriteLine($"{(i % 15 == 0 ? "FizzBuzz" : 
                             i % 3 == 0 ? "Fizz" : 
                             i % 5 == 0 ? "Buzz" : i.ToString())}");
    }
}
1
  • Here's one without using string interpolation: Console.WriteLine((i%3==0)?"Fizz"+((i%5==0)?"Buzz":"" ):(i%5==0)?"Buzz":x+""); Only shorthand if statements. Sep 26, 2016 at 16:03
4
Enumerable.Range(1, 100).ToList().ForEach(i=>Console.WriteLine($"{(i%3*i%5==0?0:i):#;}{i%3:;;Fizz}{i%5:;;Buzz}"));

This answer has it all:

  • LINQ
  • Conditional formatting
  • String interpolation
  • All on a single line

Victory!

0
3

The FizzBuzz question is a great interview question. We have started using it in our interview process. It is astounding how many people cannot solve such a simple problem.

Keep in mind, the original blog post was eventually locked due to a flood of people posting more solutions. Hahaha.

Regardless, here is mine in C++! ^_^

#include <iostream>
using namespace std;

int main(int argc, char** argv)
{
    for (int i = 1; i <= 100; ++i)
    {
        bool isMultipleOfThree = (i % 3) == 0;
        bool isMultipleOfFive = (i % 5) == 0;

        if (isMultipleOfThree) cout << "Fizz";
        if (isMultipleOfFive) cout << "Buzz";
        if (!isMultipleOfThree && !isMultipleOfFive) cout << i;

        cout << '\n';
    }

    return 0;
}
10
  • 1
    Actually, I had this solution laying around in a file already. The fact that it resembles his is merely indication of how accepted a solution it is. As far as this SO question, I just wanted to add that it is a common question.
    – TheBuzzSaw
    Aug 1, 2012 at 18:08
  • 1
    @MareInfinitus Someone who leaves optimization to the compiler has never had to build something that depends heavily on performance, or has wasted a ton of cycles dreaming that the compiler would take care of it for them. The solution being in C++ does make it better than C# because it will run at least 100x faster for that simple fact.
    – Cdaragorn
    Aug 1, 2012 at 19:45
  • 2
    @MareInfinitus The idea isn't to optimize code for the sake of optimizing...the idea is to get in the habit of optimizing code so that you don't have to think about it when you run into issues.
    – SageMage
    Aug 1, 2012 at 19:54
  • 1
    @MareInfinitus The optimization is indeed irrelevant in a program this size. However, the others are simply trying to point that you should strive to have good coding habits. Letting yourself slide because "the compiler will save me" eventually leads you to a situation where the compiler cannot optimize for you because of some ambiguity or (accidental) dependency on run-time data. No need to become defensive.
    – TheBuzzSaw
    Aug 1, 2012 at 20:07
  • 1
    @MareInfinitus I apologize that my comment seemed to be attacking you. I simply see too many ppl who go too far in the extreme in both directions (overoptimizing or not thinking about optimization at all), and try to dispel either idea when I see it presented. In this particular case, I've seen the switch from i++ to ++i make a noticable difference even in loops of only a few hundred, so it is a habit that I think everyone should try to follow, even if some languages will optimize it for you.
    – Cdaragorn
    Aug 1, 2012 at 20:13
3

Ok, what the heck, here's the solution I've come to like :)

public void DoFizzBuzz()
{
    for (int i = 1; i <= 100; ++i)
    {
        bool isDivisibleByThree = i % 3 == 0;
        bool isDivisibleByFive = i % 5 == 0;

        if (isDivisibleByThree || isDivisibleByFive)
        {
            if (isDivisibleByThree)
                cout << "Fizz";

            if (isDivisibleByFive)
                cout << "Buzz";
        }
        else
        {
            cout << i;
        }
        cout << endl;
    }
}

Obviously, this is not the fastest solution, but I like it because it emphasizes readability and makes the "FizzBuzz" case no longer a special case, but something that will happen naturally through the code path.

In the end, what I love most about this question whenever it comes up is that we get to see just how many different solutions ppl can come up with.

3

I am a beginner, here is my attempt:

public void DoFizzBuzz()
   {
       for (int i = 1; i < 101; i++)
       {

           if ((i % 3 == 0) && (i % 5 == 0))
           {
               Console.WriteLine("{0} FizzBuzz", i);
           }
           else if (i % 3 == 0)
           {
               Console.WriteLine("{0} Fizz", i);
           }
           else if (i % 5 == 0)
           {
               Console.WriteLine("{0} Buzz", i);
           }
           else
           {
               Console.WriteLine(i);
           }

       }
       Console.ReadLine();
   }

Is there anything wrong with my approach? Mine seems a lot simpler than everyone's else approach so it must be wrong.

2
  • 1
    This is the one that recruiters probably want to see. And the question was: "What would you change about it" Feb 13, 2013 at 6:14
  • 2
    There's nothing wrong with it ... there are many ways to skin a cat (as wrong as the saying is), and yours is just as good. Some use sharper knives, some use crude stone axes, some do it quick and painless, some like to bring the tribe to help, some like the cat to look pretty, some like the eat the meat and care not about it looks ...
    – Noctis
    Dec 18, 2013 at 0:14
3

You want probably make it configurable, but the question is what should be made configurable - we don't know that. Maybe we should make configurable all the cycle (FizzBuzz has the cycle). Here is very small and fun version with configurable cycle:

string[] fizzBuzzCycle = 
    "FizzBuzz,{0},{0},Fizz,{0},Buzz,Fizz,{0},{0},Fizz,Buzz,{0},Fizz,{0},{0}"
    .Split(',');

for (int i = 1; i <= 100; i++)
    Console.WriteLine(fizzBuzzCycle[i%fizzBuzzCycle.Length], i);

So if the strings or whole cycle should be changed it is easy to change. But you just don't know what to make configurable. Maybe condition will change: "for prime numbers print Pizz" and for this modification the solution by @ThomasLevesque is better, because it is easier to change.

3

I tried to solve this problem without looking at the answers. It took me 3 hours to succeed. (I'm just a hobby programmer by the way so don't bash me hard please :)) This is my c# version solution:

        static void Main(string[] args)
    {

        for (int i = 1; i <= 100; i++)
        {
            if(  ((i % 3) != 0) && ((i % 5) != 0))
            {
                WriteLine($"{i}");
            }
            else
            {
                if ((i % 15) == 0)
                {
                    WriteLine("FizzBuzz");
                }
                else if ((i % 3) == 0)
                {
                    WriteLine("Fizz");
                }
                else if ((i % 5) == 0)
                {
                    WriteLine("Buzz");
                }
            }                 
        }
    }
1
  • 1
    Sincere congrats on learning and challenging yourself. That said, you were likely downvoted because your answer does not add a new/better insight to the answers. The SO chat rooms might be a better forum for showing and getting critiques on your learning and accomplishments. Cheers. Oct 16, 2016 at 19:29
3

With no if conditions, just one ternary operator.

string[] s = new string[6]{"Fizz", "Buzz", "", "", "", ""};
for (int i = 1; i <= 100; i++)
{
    string output = s[(i%3)*2] + s[(i%5)+1];
    Console.WriteLine(string.IsNullOrEmpty(output)? "" + i : output);
}
1
  • ternary operator is a hidden "if" :-))
    – profesor79
    Mar 22 at 11:14
3

The null-coalescing operator is really useful:

string output = null;
for (int i = 1; i <= 100; i++)
{
     if (i % 3 == 0) output += "fizz";
     if (i % 5 == 0) output += "buzz";
     Console.WriteLine(output ?? i.ToString());
     output = null;
}
Console.ReadKey();
2

I recommend using the ++i instead of the i++ in a for loop because i++ requires a copy to be made ;)

public void DoFizzBuzz()
{
    for (int i = 1; i < 101; ++i)
    {
        if (i % 15 == 0)
            Console.WriteLine ("FizzBuzz");
        else if (i % 3 == 0)
            Console.WriteLine ("Fizz");
        else if (i % 5 == 0)
            Console.WriteLine ("Buzz");
        else
            Console.WriteLine (i);
    }
}
2
  • Almost the same as Thomas Levesque's solution, similar comment here Aug 1, 2012 at 17:53
  • 2
    Now there are ++i everywhere in the example. Thank you for your valuable input! Aug 1, 2012 at 20:24
2

With the input of Rob H and Jacob Krall here is what I have at the moment. Perhaps I will play around with that in future... just wanted to provide it.

public void DoFizzBuzz()
{
    // expect this to come in as parameter
    var combinations = new 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;

    // expect the borders 1, 100 to come in as parameters
    for (int i = 1; i <= 100; ++i)
    {
        var matchingCombs = combinations.Where(c => isMatch(i, c.Item1)).DefaultIfEmpty(new Tuple<int, string>(i, i.ToString())).Aggregate((v, w) => new Tuple<int, string>(v.Item1, v.Item2 + w.Item2)).Item2;
        Console.WriteLine(matchingCombs);
    }
}
2

I would suggest this compact code as an addition to the previous simple and nice versions.

for (int i = 1; i <= 100; i++) // i++ but not ++i as in your example, be careful here
{
    bool fizz = i % 3 == 0;
    bool buzz = i % 5 == 0;
    string output = fizz && buzz ? "FizzBuzz" :
                            fizz ? "Fizz" :
                            buzz ? "Buzz" :
                            i.ToString();

    Console.WriteLn(output);
}
2

A functional approach...

Console.WriteLine(Enumerable
    .Range(1,100)
    .Aggregate("", 
        (a,i) => a + "\n" + (i%15==0 ? "fizzbuzz" : 
                                (i%5==0 ? "buzz" :
                                    (i%3==0 ? "fizz" : i.ToString())))));
2

Obviously this is a bit outside the spirit of the FizzBuzz challenge. But in my benchmark this was the fastest I could make it while single threaded and still terminating at 100. It is semi-unrolled and uses a StringBuilder. It is approximately three times faster than the standard approach.

const string FIZZ = " Fizz\n";
const string BUZZ = " Buzz\n";
const string FIZZBUZZ = " FizzBuzz\n";
    ...
var sb = new StringBuilder();
int i = 0;

while(true)
{       
    sb.Append(i+3);
    sb.Append(FIZZ);        
    sb.Append(i+5);
    sb.Append(BUZZ);        
    sb.Append(i+6);
    sb.Append(FIZZ);        
    sb.Append(i+9);
    sb.Append(FIZZ);        
    sb.Append(i+10);
    sb.Append(BUZZ);        
    if(i+12 > 100)
        break;
    sb.Append(i+12);
    sb.Append(FIZZ);    
    i+=15;
    sb.Append(i);
    sb.Append(FIZZBUZZ);
}

Console.Write(sb.ToString());
2

Relatively simple solution using a for loop.

No Linq or anything - just basic shorthand if statements

for(int x=1;x<101;x++)
    Console.WriteLine(x%3==0?"Fizz"+(x%5==0?"Buzz":""):x%5==0?"Buzz":x+"");

The Linq solution which is a lot like csells (sans string interpolation) and fits on one line would be:

Enumerable.Range(1,100).ToList().ForEach(x=>Console.WriteLine(x%3==0?"Fizz"+(x%5==0?"Buzz":""):x%5==0?"Buzz":x+""));
2

I'll add mine even though there's 20 other solutions already written: It goes like this....

var x = 1;
while (x <= 100)
{
     if (x % 3 == 0 && x % 5 == 0)
        {Console.Writeline("FizzBuzz");}
     else if (x % 3 == 0)
        {Console.Writeline("fizz");}
     else if (x % 5 == 0)
        {Console.Writeline("Buzz");}
     else
        {Console.Writeline(x);}
     x++ 
}

First solution I came up with. Simple, to the point and gets the job done. No need for bool.

3
  • I saw your question about refreshing the ComboBox, and just when I was going to answer you, you erased it
    – Héctor M.
    Apr 1, 2018 at 22:46
  • Sorry I deleted it because I worded it wrong. I understand how to load a combobox but I just didn't know if I could do set up my binding differently so that I wouldn't have to refresh it manually, and it would just refresh it automatically.
    – Koosh
    Apr 1, 2018 at 22:49
  • You can use a timer that is constantly running and the Refresh () property of ComboBox
    – Héctor M.
    Apr 1, 2018 at 22:51
2

This my effort mixing Func with IEnumerable

 class Program
{
    static void Main(string[] args)
    {
        foreach (var i in FizzBuzz(100))
        {
            Console.WriteLine(i);
        }
    }

    private static IEnumerable<string> FizzBuzz(int maxvalue)
    {
        int count = 0;
        //yield return count.ToString();
        Func<int, string> FizzBuzz = (x) => ((x % 5 == 0 && x % 3 == 0) ? "FizzBuzz" : null);
        Func<int, string> Buzz = (x) => ((x % 5 == 0) ? "Buzz" : null);
        Func<int, string> Fizz = (x) => ((x % 3 == 0) ? "Fizz" : null);
        Func<int, string> Number = (x) => x.ToString();

        while (count < maxvalue)
        {
            count++;

            yield return FizzBuzz(count) ?? Buzz(count) ?? Fizz(count) ?? Number(count);
        }
    }
}
1

The original questions were: 1.How to get rid of the bool found? 2.Is there a better way of testing than the foreach?

This gets rid of the bool and the foreach, and I think it's still readable.

public static 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++)
    {
        var fb = combinations.Where(t => {
            if (i % t.Item1 == 0)
            {
                Console.Write(t.Item2);
                return true;
            }
            return false;
        }).ToList();

        if (!fb.Any())
        {
            Console.Write(i);
        }

        Console.Write(Environment.NewLine);
    }
} 

Who'd a thunk we'd be getting so excited about a simple kids game? :)

1
  • I love the fizzbuzz question. My friends from school codegolf it out sometimes.
    – Wug
    Aug 1, 2012 at 18:19
1

You can use either use this and only take the amount you want

static void Main(string[] args)
{
    GetFizzBuzz().Take(100).ToList().ForEach(Console.WriteLine);
}

private static IEnumerable<string> GetFizzBuzz()
{
    for (var i = 0; i < int.MaxValue; i++)
    {
        if (i % 3 == 0 && i % 5 == 0) yield return "FizzBuzz";
        if (i % 3 == 0) yield return "Fizz";
        yield return i % 5 == 0 ? "Buzz" : i.ToString(CultureInfo.InvariantCulture);
    }
}

Or simply use this :

Enumerable.Range(1, 100).Select(s => {
    if (s % 3 == 0 && s % 5 == 0) return "FizzBuzz";
    if (s % 3 == 0) return "Fizz";
    return s%5 == 0 ? "Buzz" : s.ToString(CultureInfo.InvariantCulture);
}).ToList().ForEach(Console.WriteLine);

Not the answer you're looking for? Browse other questions tagged or ask your own question.