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?
Luis Cadena
  • 102
  • 1
  • 2
  • 15
Mare Infinitus
  • 8,024
  • 8
  • 64
  • 113
  • 15
    Probably best for CodeReview: http://codereview.stackexchange.com/ – Chris Sinclair Aug 01 '12 at 17:47
  • Will have a look on that. I do not want other solutions, I want to improve "my" solution. – Mare Infinitus Aug 01 '12 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. – Mare Infinitus Aug 01 '12 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 01 '12 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. – Mare Infinitus Aug 01 '12 at 18:35
  • You should really check out projecteuler.net. For those that don't know it, it's like brain training for programmers. The first question is very similar to FizzBuzz and once you solve it you can post your code and view others too. You can really pick up a lot of optimization tricks from looking at other solutions. – Alex Aug 01 '12 at 19:00
  • you may be interested in some of the information here as well http://stackoverflow.com/questions/5661269/efforts-in-iteration-fizzbuzz – SageMage Aug 01 '12 at 21:37
  • @MattCase, I've recently updated the linked question to include more details and some timings. – Jodrell Jan 10 '13 at 17:50
  • I am suprised no one has mensioned the `FizzBuzzEnterpriseEdition`, arguably the best solution available: https://github.com/EnterpriseQualityCoding/FizzBuzzEnterpriseEdition. Althrough it still has its issues with thread safety: https://github.com/EnterpriseQualityCoding/FizzBuzzEnterpriseEdition/pull/282 – marcovtwout Apr 11 '19 at 14:33

47 Answers47

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);
    }
}
Thomas Levesque
  • 286,951
  • 70
  • 623
  • 758
  • This is the most straight forward version that I wrote in the first place. But it has some drawbacks, magic numbers and magic strings just to name two. So I did some refactoring and came up with the solution in the answer, which I want to improve. – Mare Infinitus Aug 01 '12 at 17:52
  • 7
    @MareInfinitus, your version also uses magic numbers and magic strings, they're just declared somewhere else... You should keep to the KISS principle ;) – Thomas Levesque Aug 01 '12 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. – Mare Infinitus Aug 01 '12 at 18:00
  • @MareInfinitus - This is exactly the point of my Linq solutions. I exactract all the bussiness logic into a single function that gets applied to the list. It exactly proper programing. I could seperate out the delegate to make it clearer... but this is exactly what Linq provides -- seperation of concerns for itterative processes. – Hogan Aug 01 '12 at 18:05
  • 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 01 '12 at 18:12
  • 1
    @TheBuzzSaw: In a real interview situation, I definitly do the simplest thing to solve the problem. But having a clever interviewer, the next question is: "what would you do about this one?" – Mare Infinitus Aug 01 '12 at 18:37
  • 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 06 '12 at 19:08
  • 1
    @Gilles, agree with you! This is just one of the best examples when a three-condition algorithm is over-complicated and as a result even looses in performance and the amount of the souce-code/memory/IL (the linq one). But of course it's interesting solution from the language-features usability. This solution is more readable as if to me many times. It's a classic solution for a classic exercise :) – Arman Jan 23 '13 at 15:29
  • 1
    The other solutions really have an overengineering problem. This is how I'd do it. It's not like it's production maintainable code, just solve the damn puzzle with simple code – Ricardo Rodrigues Jul 05 '13 at 10:26
  • It's simple but it violates the Open Close Principle – ema Jan 10 '14 at 10:10
  • 2
    @ema, uh? OCP is an OO principle; this program isn't even object oriented, how can it violate OCP? – Thomas Levesque Jan 10 '14 at 10:23
  • @ThomasLevesque OCP can be applied also to functional programming or other paradigms. It is a general principle for writing maintainable software. Isn't it? – ema Jan 12 '14 at 15:34
  • 2
    @ema, in my mind it has always been related to object-oriented programming (the [Wikipedia article](http://en.wikipedia.org/wiki/Open/closed_principle) seems to agree), but I might be wrong. Anyway, I wrote this code to solve the problem in the simplest possible way; I didn't even try to make it extensible... – Thomas Levesque Jan 12 '14 at 17:32
  • To make it even simpler and more time efficient, wouldn't the addition of another variable for FizzBuzz help? like: bool fizzbuzz = i % 15 == 0; – Ricardo Sanchez Nov 03 '15 at 01:57
  • 2
    @RicardoSanchez I know this is an old topic, but just to add to your comment for anyone who stumbled across this and was curious about your question... I wouldn't add a fizzBuzz like that. If I had to, I'd add bool fizzBuzz = fizz && buzz; The reason being that you're not then duplicating the "logic" of the calculation (DRY). However, I think having a fizzBuzz variable would be unnecessary and the current answer is good enough. If I were to be picky, the only changes I'd make would be to separate the logic from the output...but that is being picky and the given answer works! – Wayne Feltham Aug 21 '17 at 10:45
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;
    }
}
Wug
  • 12,956
  • 4
  • 34
  • 54
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);
}
MikeP
  • 7,829
  • 33
  • 34
  • what the heck, this one is crazy! ... so +1 ;) – Mare Infinitus Aug 01 '12 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. – Tony_Henrich Jan 28 '15 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 '16 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 '16 at 02:39
  • 2
    @SageMage Code golf challenges for simple problems can give you a better understanding of the syntax. – lordcheeto Sep 28 '16 at 02:43
  • Oh, and `++i` to increment i with one less character than in the for loop. `class C{static void Main(){for(int i=0;i<100;)System.Console.Write($"{(++i%3*i%5<1?0:i):#}{i%3:;;Fizz}{i%5:;;Buzz}\n");}}` – lordcheeto Sep 28 '16 at 02:48
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.

Yuval Itzchakov
  • 146,575
  • 32
  • 257
  • 321
Rob H
  • 1,840
  • 16
  • 25
  • LINQ helps even here! I like that one! +1! Possible candidate for accept! – Mare Infinitus Aug 01 '12 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 01 '12 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 – Jacob Krall Aug 01 '12 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. – Mare Infinitus Aug 01 '12 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 01 '12 at 18:20
  • @JacobKrall Found a way to join it, have provided an own answer, but did accept this one here. Thank you all for the valueable input! – Mare Infinitus Aug 01 '12 at 19:47
  • Every interview I've been in with Fizz Buzz has asked 'Now solve it a more creative way' or 'Now solve it without using a loop'. I really like this answer, using `Func<>` can't fail to get you bonus points in an interview :) – NibblyPig Aug 15 '12 at 09:38
  • Someone just copy/pasted this solution with a couple of modifications. Also your solution prints the number as well as Fizz Buzz or FizzBuzz. FizzBuzz specifically says "Instead of". – Omar Kooheji Sep 01 '14 at 11:25
  • Well I'm flattered! I wonder if it was the same person who upvoted this answer about a week ago... Anyway, you're right and there's another bug in the solution that I haven't bothered to fix yet. Maaybe I shouldn't as it gives it a unique 'signature'! :) – Rob H Sep 02 '14 at 03:27
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())
      ));
    }
}
Hogan
  • 69,564
  • 10
  • 76
  • 117
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.

Jason Down
  • 21,731
  • 12
  • 83
  • 117
14

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);
shenku
  • 11,969
  • 12
  • 64
  • 118
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
    }
Shivprasad Koirala
  • 27,644
  • 7
  • 84
  • 73
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());
fxdxpz
  • 1,969
  • 17
  • 29
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()));
Xela
  • 2,322
  • 1
  • 17
  • 32
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();
}
Sai
  • 682
  • 2
  • 12
  • 35
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())}");
    }
}
Yuval Itzchakov
  • 146,575
  • 32
  • 257
  • 321
  • 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. – user1274820 Sep 26 '16 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!

csells
  • 2,453
  • 1
  • 20
  • 18
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;
}
TheBuzzSaw
  • 8,648
  • 5
  • 39
  • 58
  • This is the C++ version of Thomas Levesque's C# version. See my comment there please. – Mare Infinitus Aug 01 '12 at 18:07
  • 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 01 '12 at 18:08
  • This is better than Thomas Levesque's version. Reasons-- #1 it is in C++ #2 this is about as optimized as you can get as far as performance is concerned. – SageMage Aug 01 '12 at 18:09
  • First: Having it in C++ does not make it better itself. Second: optimization is best left to the compiler, especially in simple cases. – Mare Infinitus Aug 01 '12 at 18:30
  • 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 01 '12 at 19:45
  • microoptimizations are the hell, often slower than compiler optimized code. There are lots of examples on how to optimize **and** why it is reasonable only to optimize when in need. This example here will definitly be fast enough even in C#. I have developed in C++ for 14 years now, even some performance crititcal code, and here (FizzBuzz) I do not see where I should optimize. perhaps you have heard of loop transformations that a compiler will do? no human would write such code. – Mare Infinitus Aug 01 '12 at 19:52
  • 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 01 '12 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 01 '12 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 01 '12 at 20:13
  • 1
    No problem. An the other side, I see lots of people thinking about ++i or i++ and have no ideas of good system design and how to tackle a more than "hello world" problem. Perhaps, we would have very similar expectations on what code should be like. – Mare Infinitus Aug 01 '12 at 20:20
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.

Cdaragorn
  • 344
  • 3
  • 10
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.

stirredo
  • 2,297
  • 3
  • 19
  • 23
  • 1
    This is the one that recruiters probably want to see. And the question was: "What would you change about it" – Mare Infinitus Feb 13 '13 at 06: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 '13 at 00: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.

CoperNick
  • 2,413
  • 2
  • 21
  • 26
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
    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. – Andrew Hanlon Oct 16 '16 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);
}
pythonic
  • 20,589
  • 43
  • 136
  • 219
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();
Donnoh
  • 161
  • 10
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);
    }
}
SageMage
  • 1,096
  • 8
  • 16
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);
    }
}
Mare Infinitus
  • 8,024
  • 8
  • 64
  • 113
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);
}
Arman
  • 5,136
  • 3
  • 34
  • 36
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())))));
EFVincent
  • 103
  • 1
  • 6
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+""));
user1274820
  • 7,786
  • 3
  • 37
  • 74
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());
Andrew Hanlon
  • 7,271
  • 4
  • 33
  • 53
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.

Koosh
  • 876
  • 13
  • 26
  • I saw your question about refreshing the ComboBox, and just when I was going to answer you, you erased it – Héctor M. Apr 01 '18 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 01 '18 at 22:49
  • You can use a timer that is constantly running and the Refresh () property of ComboBox – Héctor M. Apr 01 '18 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);
        }
    }
}
fkerrigan
  • 270
  • 2
  • 9
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? :)

grahamesd
  • 4,773
  • 1
  • 27
  • 27
  • I love the fizzbuzz question. My friends from school codegolf it out sometimes. – Wug Aug 01 '12 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);
Kevin Moore
  • 179
  • 7
1

Found Stringbuilder to be the fastest.

I find this implementation the easiest to read as well.

public static void FizzBuzz() {

    StringBuilder sb = new StringBuilder();

    for (int i = 1; i <= 100; i++) {    
        if (i % 3 == 0 && i % 5 == 0) {
            sb.AppendLine($"{i} - FizzBuzz");
        } else if (i % 3 == 0) {
            sb.AppendLine($"{i} - Fizz");
        } else if (i % 5 == 0) {
            sb.AppendLine($"{i} - Buzz");
        } else {
            sb.AppendLine($"{i}");
        }
    }
    Console.WriteLine(sb);
}
levis84
  • 974
  • 1
  • 12
  • 27
0

Without using any If's, C# code.

 //False = 0, True = 1.
    private void DivisibilityByFiveThreeTest(int num)
    {
        string[,] values = new string [2,2]{
                             {"None","Fizz"},
                             {"Buzz","FizzBuzz"}
                             };
        for(int i=1;i< num;i++)
        Console.WriteLine(values[Convert.ToInt32(i % 5 == 0), Convert.ToInt32(i%3==0)]);

    }
CodeR
  • 156
  • 1
  • 8
0

straight forward solution in JavaScript

var i = 1;
while (i <= 100){
    console.log((i % 3 === 0 && i % 5 === 0) ? "FizzBuzz" : (i % 3 === 0) ? "Fizz" : (i % 5 === 0 ? "Buzz" : i));
    i++;
}
Enogwe Victor
  • 70
  • 1
  • 5
0

In python.....

 for i in range(0, 100) :
        a = i % 3 == 0
        b = i % 5 == 0

        if(a & b):
            print("FizzBuzz")
        elif(a):
            print("Fizz")
        elif(b):
            print("Buzz")
        else:
            print(i)
Michael Mburu
  • 460
  • 1
  • 4
  • 11
0

C++ implementation

vector<string> FizzBuzz::execute(int n) {

    if(n == 0)
        return vector<string>();

    auto push = n % 15 == 0 ? "fizzbuzz" :
                n % 3 == 0 ? "fizz" :
                n % 5 == 0 ? "buzz" :
                to_string(n);

    auto execution = execute(n-1);
    execution.push_back(push);
    return execution;
}
Tommaso Resti
  • 5,800
  • 4
  • 18
  • 34
0
In C#...

using System;
using System.IO;
class Solution {
    static void Main(String[] args) {        
        for(int i=1;i<=100;i++)
        {                       
         string result=(i%3==0 && i%5==0) ? "FizzBuzz" : 
               (i%5==0) ? "Buzz" :
                       (i%3==0) ? "Fizz" : i.ToString();            
         Console.WriteLine(res);
        }
    }
}


In VB.NET...

Imports System
Imports System.IO

Class Solution
    Private Shared Sub Main(ByVal args As String())
        For i As Integer = 1 To 100
            Dim res As String = If((i Mod 3 = 0 AndAlso i Mod 5 = 0), "FizzBuzz", If((i Mod 5 = 0), "Buzz", If((i Mod 3 = 0), "Fizz", i.ToString())))
            Console.WriteLine(res)
        Next
    End Sub
End Class
0

Been answered to death but just to show another solution that answers the actual question

public static void DoFizzBuzz()
{
    var combinations = new (int multiple, string output)[]
    {
        (3, "Fizz"),
        (5, "Buzz")
    };

    for (int i = 1; i <= 100; ++i)
    {
        // Seed the accumulation function with an empty string and add any 'matches' from each combination
        var fb = combinations.Aggregate("", (c, comb) => c + (i % comb.multiple == 0 ? comb.output : ""));

        Console.WriteLine(!string.IsNullOrEmpty(fb) ? fb : $"{i}");
    }
}
SteveHayles
  • 168
  • 1
  • 7
0

This is an answer written in JavaScript

//returns true if modulus is zero and is reusable        
var isModulusZero = (challenge, modulator) => {
    let answer = challenge % modulator;

    if (answer == 0) {
        return true
    } else {
        return false
    }
}

var printOneToHundred = () => {
    var i = 1;

    for (i; i <= 100; i++) {

        if (isModulusZero(i, 3) && isModulusZero(i, 5)) {
            console.log('FizzBuzz')
        } else if (isModulusZero(i, 3)) {
            console.log('Fizz')
        } else if (isModulusZero(i, 5)) {
            console.log('Buzz')
        } else {
            console.log(i)
        }

    }
}
0

Ok - I'll bite. The LINQ heavy solution I came up with on a recent initial coding interview. Amazing how many different solutions there are to this simple problem.

public static class FizzBuzzUtils
{
    private static List<KeyValuePair<int, string>> map = new List<KeyValuePair<int, string>> {
        new KeyValuePair<int, string>(3, "Fizz"),
        new KeyValuePair<int, string>(5, "Buzz")
    };

    public static string GetValue(int i)
    {
        var matches = map.Where(kvp => i % kvp.Key == 0)
            .Select(kvp => kvp.Value)
            .ToArray();
        return matches.Length > 0 ? string.Join(string.Empty, matches) : i.ToString();
    }

    public static IEnumerable<string> Range(int start, int count)
    {
        return Enumerable.Range(start, count)
            .Select(i => GetValue(i));
    }
}
Casey Chester
  • 268
  • 3
  • 11
0

Fizz Buzz Pattern (see CachedFizzBuzz method), combined with strategy pattern.

using System;
interface IFizzBuzz
{
}
class NullFizzBuzz: IFizzBuzz
{
    public static int value;
     public override string ToString()
    {
        return value.ToString();
    }
}
class Buzz : IFizzBuzz
{
    public override string ToString()
    {
        return "Buzz";
    }
}
class Fizz: IFizzBuzz
{
    public override string ToString()
    {
        return "Fizz";
    }
}
class FizzBuzz : IFizzBuzz
{
    public override string ToString()
    {
        return "FizzBuzz";
    }
}

class FizzBuzzSolver
{
    public int Fizz { get; }
    public int Buzz { get; }
    public int Iterations { get; }
    public int FizzBuzz { get; }
    public int Quotient { get; }
    public int Remainder { get; }
    public FizzBuzzSolver(int fizz, int buzz, int iterations, int fizzbuzz, int quotient, int remainder)
    {
        Fizz = fizz;
        Buzz = buzz;
        Iterations = iterations;
        FizzBuzz = fizzbuzz;
        Quotient = quotient;
        Remainder = remainder;
    }

    internal void Solve(Action<FizzBuzzSolver> fizzBuzz)
    {
        fizzBuzz(this);
    }
}
class Program
{
    static void Main()
    {
        int fizz = 3;// int.Parse(Console.ReadLine());
        int buzz = 5;// int.Parse(Console.ReadLine());
        int iterations = 100;//int.Parse(Console.ReadLine());
        int fizzbuzz = fizz * buzz;
        int quotient = Math.DivRem(iterations, fizzbuzz, out var remainder);
        FizzBuzzSolver fb = new FizzBuzzSolver(fizz, buzz, iterations, fizzbuzz, quotient, remainder);
        switch (quotient)
        {
            case 0: fb.Solve(RemainderFizzBuzz); break;
            case 1: fb.Solve(NormalFizzBuzz);  break;
            default: fb.Solve(CachedFizzBuzz); break;
        };

        Console.Read();
    }

    private static void NormalFizzBuzz(FizzBuzzSolver fb)
    {
        for (int i = 1; i < fb.FizzBuzz; i++)
        {
            Console.WriteLine(i % fb.Fizz == 0 ? "Fizz" : i % fb.Buzz == 0 ? "Buzz" : i.ToString());
        }
        Console.WriteLine("FizzBuzz");
        for (int i = fb.FizzBuzz+1; i <= fb.Iterations; i++)
        {
            Console.WriteLine(i % fb.Fizz == 0 ? "Fizz" : i % fb.Buzz == 0 ? "Buzz" : i.ToString());
        }
    }

    private static void CachedFizzBuzz(FizzBuzzSolver fb)
    {
        var fizzbuzzArray = new IFizzBuzz[fb.FizzBuzz];

        for (int i = 0; i < fb.FizzBuzz - 1; i++)
        {
            int s = i + 1;
            if (s % fb.Fizz == 0)
            {
                fizzbuzzArray[i] = new Fizz();
                Console.WriteLine("Fizz");
            }
            else
            if (s % fb.Buzz == 0)
            {
                fizzbuzzArray[i] = new Buzz();
                Console.WriteLine("Buzz");
            }
            else
            {
                fizzbuzzArray[i] = new NullFizzBuzz();
                Console.WriteLine(s);
            }

        }
        fizzbuzzArray[fb.FizzBuzz - 1] = new FizzBuzz();
        Console.WriteLine("FizzBuzz");
        NullFizzBuzz.value = fb.FizzBuzz;
        for (int j = 1; j < fb.Quotient; j++)
        {
            for (int i = 0; i < fb.FizzBuzz; i++)
            {
                NullFizzBuzz.value++;
                Console.WriteLine(fizzbuzzArray[i]);
            }

        }
        for (int i = 0; i < fb.Remainder; i++)
        {
            NullFizzBuzz.value++;
            Console.WriteLine(fizzbuzzArray[i]);
        }
    }

    private static void RemainderFizzBuzz(FizzBuzzSolver fb)
    {
        for (int i = 1; i <= fb.Remainder; i++)
        {
            Console.WriteLine(i % fb.Fizz == 0 ? "Fizz" : i % fb.Buzz == 0 ? "Buzz" : i.ToString());
        }
    }
}
Deepak Mishra
  • 2,984
  • 1
  • 26
  • 32
0

Unlike other answers here, this solution offers the possibility of easily extending it. If an interviewer were to ask you to e.g. also replace 7 with "Woof", it is easily done by adding to the map.

var map = new Dictionary<int, string>
{
    {3*5*7, "FizzBuzzWoof"}, // Optional
    {5*7, "BuzzWoof"}, // Optional
    {3*7, "FizzWoof"}, // Optional
    {3*5, "FizzBuzz"},
    {7, "Woof"},
    {5, "Buzz"},
    {3, "Fizz"},
    {1, null} // For all numbers not evenly divisible
};

var words = Enumerable
    .Range(0, 154)
    .Select(i => (i == 0 ? null : map[map.Keys.First(k => i % k == 0)]) ?? i.ToString())
    .Dump("Words");

string.Join(' ', words).Dump("Result");

Identifying all permutations, however, becomes a chore, and the more extra words are added, the more lookups will be made, but the point is to argue about understanding coding principles.

Reyhn
  • 997
  • 1
  • 11
  • 22
0

Since we are going for a generic FizzBuzz (I've seen this called Raindrops), there are a couple simple modifications to keep it generic and more readable:

  1. Renaming 'combinations' to 'primeFactors' makes it a little more descriptive
  2. Tuple field names to make accessing tuple fields more readable
  3. Linq to query the list of prime factors for the display strings we want (removing the foreach)
    • Where filters the list to factors of the current integer
    • Select transforms the matching factors into their display string
    • DefaultIfEmpty handles the 'no match found' case allowing us to remove that boolean
    • Aggregate concatenates all the matching display strings together

Try it online!

public void DoFizzBuzz()
{
    var primeFactors = new (int Factor, string Display)[]
    {
        (3, "Fizz"),
        (5, "Buzz")
    };
    for (var integer = 1; integer <= 100; ++integer)
        Console.WriteLine(primeFactors
            .Where(tuple => integer % tuple.Factor == 0)
            .Select(tuple => tuple.Display)
            .DefaultIfEmpty($"{integer}")
            .Aggregate((first, second) => $"{first}{second}")
        );
}
NonlinearFruit
  • 2,509
  • 1
  • 25
  • 27
0
var min = 1;
var max = 100;

for (var i = min; i <= max; i++)
{
    if (i % 3 == 0) { goto fizz; }

checkBuzz:
    if (i % 5 == 0) { goto buzz; }
    goto writeNumber;

fizz:
    Console.Write("Fizz");
    goto checkBuzz;

buzz:
    Console.Write("Buzz");
    goto allDone;

writeNumber:
    if (i % 3 != 0) { Console.Write(i); }

allDone:
    Console.WriteLine();
}
user1325543
  • 523
  • 3
  • 12
0

My final approach to FizzBuzz in C#.

There are countless solutions to the FizzBuzz test but few meet my requirements in crisp clear, readable, clean and maintainable code. Let me just say what I mean with

  1. clear: isolate a task into kind of logic atoms and encapsulate them inside a type
  2. readable: think of identifier names that describe and fit to the task; format your code
  3. clean: design the members of the type with as little “noise” as possible
  4. maintainable: maybe you want to or have to extend the type in the future. think of a layout that will allow that

Here is the solution I came up with. A static class that handles the task.

My first question was: what are the possible states of FizzBuzz? Ok, either FIZZ or BUZZ, that's clear. And there is also the FIZZBUZZ state if the number can be divided by 3 and 5 at the same time. Hm, interesting. This can be regarded as a (logical) sum of FIZZ + BUZZ… Finally, the state NONE (or 0) remains if neither state fits.

As an experienced developer with old low level skills (asm), I decided to use a so-called bit vector (binary flags) to fit my task. The .NET framework also makes heavy use of these when it comes to configuration options and offers a comfortable C# language construct, the enum type. Due to public visibility, I name this enum Category to depict the possible states.

Next there are the intern FIZZ and the BUZZ functions that perform the divisibility test on the given number and return the appropriate category.

Finally the only publicly available function named “test” allows us to test a given number. It returns the number’s state as defined in Category. The trick here is, that the function calls both members fizz and buzz and combines or adds (ok, boolean ORs) their results to the proper state.

I was also experimenting with some functional approaches using lambdas but these had no advantages over the solution shown. I like to keep things simple.

Happy coding,

Tom

Download Gist: https://gist.github.com/tomschrot/da0bd69dd1e591fa3da43c1fdb3e4f85

WriteLine ("Final FizzBuzz in C#\nby Tom Schröter\n");

for (int n = 1; n <= 100; n++)
    WriteLine ("{0,3}: {1}", n, FizzBuzz.test(n));

WriteLine ($"\r\nOK @ {DateTime.Now}");

static class FizzBuzz
{
    public enum Category: uint { NONE = 0, FIZZ = 0b0001, BUZZ = 0b0010, FITZBUZZ = 0b0011 };

    private static Category fizz (int n) => n % 3 == 0 ? Category.FIZZ : Category.NONE;
    private static Category buzz (int n) => n % 5 == 0 ? Category.BUZZ : Category.NONE;

    public  static Category test (int n) => fizz (n) | buzz (n);
}
tomschrot
  • 219
  • 1
  • 2
  • 4
0

The amount of people here using the most complex and over the top ways to do this very simple task hurts my head. This problem does not need three if statements, something the OP did get right. This was my quick solution:

    for (int i = 1; i<=100; ++i) {
        string printValue = string.Empty;
        printValue += (i%3==0)? "Fizz" : string.Empty;
        printValue += (i%5==0)? "Buzz" : string.Empty;
        if (printValue != string.Empty) Console.WriteLine(printValue);
    }

It avoids using nested loops, there are only two situations to check and storing them in a tuple array is adding complexity to the code with little if any performance or readability gain, but otherwise you had a unique take on it. Im interested if you have programmed in another language, since you used ++i over i++ in your for loop, both work the same in a for loop but the pre increment is slightly more performant, I didn't learn this for a very long time.

As for my code, you can technically just put the condition check into an if statnemt to avoid adding string.Empty to print value if you so wish, but I like the look of this format. You can also more than likely do it in only 3 or so lines, but it gets hard to read.

Now for anyone who has or wants to provide a solution of their own, you can easily simplify this down and use a lookup table or something like that, but the task that was asked was to check EACH number and print a value based on its divisibility. As a programmer, its important to focus on what was asked, not what you think is better. Too many times we will get caught up in trying to outdo ourselves or each other and end up producing something that is either-

  • A- Unreadable
  • B- Unextendible
  • C- Incorrect
  • D- Not what the person actually asked for
ZXYNINE
  • 712
  • 4
  • 5
0

As of C# 8.0 you can use tuple pattern matching to solve FizzBuzz.

foreach (var item in Enumerable.Range(1, 100).Select(FizzBuzz))
{
    Console.WriteLine(item);
}

static string FizzBuzz(int number)
{
    return (number % 3, number % 5) switch
    {
        (0, 0) => "FizzBuzz",
        (0, _) => "Fizz",
        (_, 0) => "Buzz",
        _ => number.ToString(),
    };
}

Sample based upon this answer.

DaemonFire
  • 573
  • 6
  • 13
-1

The shortest answer!!!

have a read.... look i mean:

for(;++$i<101;)print($i%15?$i%3?$i%5?$i:Buzz:Fizz:FizzBuzz)."\n"

Language PHP. Enjoy.

Sweet Chilly Philly
  • 3,014
  • 2
  • 27
  • 37