Some Interesting FizzBuzz Solutions
FizzBuzz is fairly easy. But that’s where you can put constraints on it. Spoiler alert: Don’t read this if you want to figure some of these out yourself.
The problem, recap
For numbers from 1 to 100 (inclusive), print “Fizz” for multiples of 3, “Buzz” for multiples of 5, and the number itself for others. (Goes without saying that when the number is divisible by 3 and 5, you print “FizzBuzz”)
Solutions
Using match and guard (rust)
fn main() {
for i in 1..=100 {
match (i % 3, i % 5) {
(0, 0) => println!("FizzBuzz"),
(0, _) => println!("Fizz"),
(_, 0) => println!("Buzz"),
(_, _) => println!("{i}")
}
}
}
Using mutation (python)
for i in range(1, 101):
x = ""
if i % 3 == 0: x = "Fizz"
if i % 5 == 0: x = x + "Buzz"
if x == "": x = str(i)
print(x)
Using closures and array indexing (javascript)
const print = (a, b, c) => console.log(a + b || c)
const counter = (list) => (i) => list[i % list.length]
const three = counter(["","","Fizz"])
const five = counter(["","","","","Buzz"])
for (let i = 0; i < 100; i++) {
print(three(i), five(i), i+1);
}
Or slightly differently
const print = (a, b, c) => console.log(a + b || c)
const counter = (at, word) => (i) => i % at === 0 ? word : ""
const three = counter(3, "Fizz")
const five = counter(5, "Buzz")
for (let i = 1; i <= 100; i++) {
print(three(i), five(i), i);
}
Using repetition (python)
for i in range(0, 7):
x = i * 15
print(x + 1)
print(x + 2)
print("Fizz")
print(x + 4)
print("Buzz")
print("Fizz")
print(x + 7)
print(x + 8)
print("Fizz")
print("Buzz")
if i == 6: continue
print(x + 11)
print("Fizz")
print(x + 13)
print(x + 14)
print("FizzBuzz")
Using multiplication table and set intersection (python)
threes = set(x * 3 for x in range(0, 34))
fives = set(x * 5 for x in range(0, 21))
fifteens = threes.intersection(fives)
d = {
**dict.fromkeys(threes, "Fizz"),
**dict.fromkeys(fives, "Buzz"),
**dict.fromkeys(fifteens, "FizzBuzz")
}
for i in range(1, 101):
print(d.get(i, str(i)))
Using carriage returns (python)
This might not pass certain automated tests.
But for a human the output is right.
It is like the mutation solution, except it happens on the tty.
for i in range(1, 101):
print(i, end='\r')
if i % 3 == 0: print("Fizz", end="")
if i % 5 == 0: print("Buzz", end="")
print()
Mask
m = ("..f.bf..fb.f..z" * 7)[0:100]
d = {'f': "Fizz", 'b': "Buzz", 'z': "FizzBuzz"}
for i, x in enumerate(list(m)):
print(d.get(x, i+1))
That can actually be shortened to this one-liner
print(*[{'f': "Fizz", 'b': "Buzz", 'z': "FizzBuzz"}.get(x,i+1) for i,x in enumerate(list(("..f.bf..fb.f..z" * 7)[0:100]))], sep='\n')
Using mathematics for mask
I took help from reddit for this
for x in range(100):
print(x % 3 // 2 * "Fizz" + x % 5 // 4 * "Buzz" or x + 1)
This works because //
operator can only give the integer part of the division. So, it returns 1 every 3rd or 5th iteration. or
works like ||
in javascript.