EDIT For what its worth, which admittedley may not be that much. I've done a little test to expand this question.
I've written two functions to enumerate the FizzBuzz "series."
private static IEnumerable<string> SimpleFizzBuzz(
int start = 0,
int end = int.MaxValue)
{
return Enumerable.Range(start, end).Select(i =>
i % 15 == 0 ? "fizzbuzz" :
i % 3 == 0 ? "fizz" :
i % 5 == 0 ? "buzz" :
i.ToString(CultureInfo.InvariantCulture));
}
and,
private static IEnumerable<string> OptimizedFizzBuzz(
int start = 0,
int end = int.MaxValue)
{
const int fizz = 3;
const int buzz = 5;
const string fizzString = "fizz";
const string buzzString = "buzz";
const string fizzBuzzString = fizzString + buzzString;
var fizzer = start % fizz;
var buzzer = start % buzz;
if (fizzer == 0)
{
fizzer = fizz;
}
if (buzzer == 0)
{
buzzer = buzz;
}
for (var i = start; i <= end; i++)
{
if (buzzer == buzz)
{
if (fizzer == fizz)
{
yield return fizzBuzzString;
buzzer = 1;
fizzer = 1;
continue;
}
yield return buzzString;
buzzer = 1;
fizzer++;
continue;
}
if (fizzer == fizz)
{
yield return fizzString;
buzzer++;
fizzer = 1;
continue;
}
yield return i.ToString(CultureInfo.InvariantCulture);
fizzer++;
buzzer++;
}
}
I've done a little timing, compiled in Release configuration, with optimizations and run from the command line. Over 10^8
iterations, without the overhead of actually reporting each item, I get results that approximate to,
Simple: 14.5 Seconds
Optimized: 10 Seconds
You'll note that the "optimized" function is faster but more verbose. It's behaviour can be altered simply by changing the constants at its head.
Apologies if this seems a little trivial.
Consider this function.
using System.Text;
public string FizzBanger(int bound)
{
StringBuilder result = new StringBuilder();
for (int i = 1; i < bound; i++)
{
String line = String.Empty;
if (i % 3 == 0) line += "fizz";
if (i % 5 == 0) line += "buzz";
if (String.IsNullOrEmpty(line)) line = i.ToString();
result.AppendLine(line.ToString());
}
return result.ToString();
}
The output will look like
1
2
fizz
4
buzz
fizz
7
8
fizz
buzz
11
fizz
13
14
fizzbuzz
16
...
Can anybody think of a better way of doing it? Please consider both performance and maintainability.