FizzBuzz is a simple yet potentially deceiving minor task many engineers, from budding to experienced, will encounter. It has a very simple explanation as follows:
Craft some code that outputs the numbers from 1 to 100. When the number is a multiple of three print "Fizz" instead of the number and for the multiples of five print "Buzz". For numbers which are multiples of both three and five print "FizzBuzz".
Quite typically this is looks in the most basic form as follows:
static void Main(string[] args)
{
for (int i = 0; i <= 100; i++)
{
if (i % 3 == 0 && i % 5 == 0)
{
Console.WriteLine("FizzBuzz");
}
else if (i % 3 == 0)
{
Console.WriteLine("Fizz");
}
else if (i % 5 == 0)
{
Console.WriteLine("Buzz");
}
else
{
Console.WriteLine(i);
}
}
}
This is a wonderful basic implementation, however we have improvements that could be considered here.
Could we improve the length of this code to make it more concise
Could we limit the number of commands to only call the write once, and not multiple times.
We can easily perform both items one and two with a simple application of Linq and a bit of string interpolation as follows:
static void Main(string[] args)
{
var fizzBuzz = Enumerable.Range(1, 100).Select(i => {
var isFizz = i % 3 == 0;
var isBuzz = i % 5 == 0;
return $"{(!isFizz && !isBuzz ? i.ToString() : string.Empty)}{(isFizz ? "Fizz" : string.Empty)}{(isBuzz ? "Buzz" : string.Empty)}";
});
Console.WriteLine(string.Join("\r\n", fizzBuzz));
}
Here we can create an IEnumerable range of integers as specified, and allow the linq iterator to create an output IEnumerable of strings based on our valuation checks. Once completed, we will be able to simply join these items together with a carriage return and output in one go.
While it may seem frivolous to combine these, in larger segments where time may be more important we could shave loads of processor time and result return time. However we are not covering all of the potential problems. Later I will cover some of the other basic issues with string manipulation and how we can time the difference between these, for our purposes in this small example, we have accomplished some small time savings by not writing many times over for one use, as well as shorten our code to be more readable.
While I know many people loathe ternary operations, and I wholly agree when you have nested ternaries, since these are a side-by-side of three we have more clearly shown the whole process in only a few lines.
There are many more changes that could be done, as a way to add some accents to your work and display more deep understanding. If for instance this wasn’t just a simple modulus, but a series of calls to an api over HTTP, we could save vast amounts of time by performing these actions as an asynchronous batch with Task.WhenAll(…)
How would you enhance this process, and how would you apply those advancements to other problems?