Last active
May 16, 2020 06:26
-
-
Save lpnam0201/e971c4caa8460663012df8e853f2a293 to your computer and use it in GitHub Desktop.
FizzBuzz without conditional C#
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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 16 % 5 is 1 so we "turn on"
mod5Map[1]
, we get 001 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".