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:
- How to get rid of the bool found?
- Is there a better way of testing than the foreach?
Not the most efficient, but here's one using C#-6 string interpolation:
Relatively simple solution using a for loop.
No Linq or anything - just basic shorthand if statements
The Linq solution which is a lot like csells (sans string interpolation) and fits on one line would be:
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++! ^_^
You can use either use this and only take the amount you want
Or simply use this :
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:
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.
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: