FizzBuzz

One thing I like to do in my free time is answer popular interview questions in creative ways. These are a couple examples that I have created over time to solve the FizzBuzz interview question in a Code Golf esque style. These solutions are intentionally hard to read so be prepared! I added comments to explain the code a little at least a little bit.

Javascript

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
// function to check if input i is divisible by 3
const isFizz = (i) => (i % 3 == 0);

// function to check if input i is divisible by 5
const isBuzz = (i) => (i % 5 == 0);

// function to check if input i is divisibly by 3 and 5
const isFizzBuzz = (i) => ((i % 3 == 0) && (i % 5 == 0));

// Loop through numbers 1 to 100
for (let i = 1; i <= 100; i++) {
// Use the functions to output
// - FizzBuzz: If current number is divisible by 3 and 5
// - Fizz: If current number is divisible by 3
// - Buzz: If current number is divisible by 5
// - Number: If none of these apply
//
// We're heavily using ternary operators to reduce the code
console.log(isFizzBuzz(i) ? 'FizzBuzz' : isFizz(i) ? 'Fizz' : isBuzz(i) ? 'Buzz' : i);
}

Swift

This solution is also in my Swift Playground Repository

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
// Loop through numbers 1 to 100
for i in 1...100 {
// Create a String "message" containing our output
// - FizzBuzz: If current number is divisible by 3 and 5
// - Fizz: If current number is divisible by 3
// - Buzz: If current number is divisible by 5
// - Number: If none of these apply
//
// We're again heavily using ternary operators to reduce the code
guard let message: String =
((i % 3 == 0) && (i % 5 == 0)) ? "FizzBuzz" :
(i % 3 == 0) ? "Fizz" :
(i % 5 == 0) ? "Buzz" : nil else {
print(i)
continue
}

// print the message
print(message)
}