Skip to content

Instantly share code, notes, and snippets.

@lpnam0201
Last active May 16, 2020 06:26
Show Gist options
  • Save lpnam0201/e971c4caa8460663012df8e853f2a293 to your computer and use it in GitHub Desktop.
Save lpnam0201/e971c4caa8460663012df8e853f2a293 to your computer and use it in GitHub Desktop.
FizzBuzz without conditional C#
using System;
public class Program
{
public static void Main()
{
var funcs = new Func<int, string>[4]
{
n => n.ToString(),
n => "Fizz",
n => "Buzz",
n => "Fizz Buzz"
};
var mod3Map = new int[3] { 1, 0, 0 };
var mod5Map = new int[5] { 1, 0, 0, 0 , 0 };
for (int i = 1; i < 100; i++)
{
int mod3 = i % 3;
int digit0 = mod3Map[mod3];
int mod5 = i % 5;
int digit1 = mod5Map[mod5];
var funcIndex = digit0 * 1 + digit1 * 2;
var text = funcs[funcIndex](i);
Console.WriteLine(text);
}
}
}
@lpnam0201
Copy link
Author

lpnam0201 commented May 16, 2020

It maps the divisibility by 3 or 5 of a number to 4 different states of 00, 01, 10, 11, which will translate to the index that contains the corresponding function.
Given number 6 for example.
mod3Map = [1, 0, 0]
mod5Map = [1, 0, 0, 0, 0]
6 % 3 is 0 so we "turn on" mod3Map[0], we get 1
6 % 5 is 1 so we "turn on" mod5Map[1], we get 0
01 state corresponds to number 1 in decimal (here I use most significant digit first, so we have 0 * 2^1 + 1 * 2^0) , so we use the second stored function and get "Fizz".

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment