Let’s make this idea of posts i have more interesting.
From now on this will be a Wiki for who wants to add a language. Please comment below which languages you have added or contributed.
The problem this time is FizzBuzz.
FizzBuzz is a program that prints the numbers from 1 to 100. But for multiples 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”.
Because this is sometimes used in interviews to test basic programming skills, I will only add one example and hope you all to contribute in other languages.
Python one-liner
for i in range(1,101): print("FizzBuzz" if i%15==0 else "Fizz" if i%3==0 else "Buzz" if i%5==0 else i)
Python (switch)
for i in range(1, 101):
match i % 15:
case 0:
print("FizzBuzz")
case 3 | 6 | 9 | 12:
print("Fizz")
case 5 | 10:
print("Buzz")
case _:
print(i)
JS one-liner
new Array(101).fill(0).forEach((_, i) => console.log(i % 3 === 0 && i % 5 === 0 ? "FizzBuzz" : (i % 3 === 0 ? "Fizz" : (i % 5 === 0 ? "Buzz" : i))))
JavaScript (switch):
for (let i = 1; i <= 100; i++) {
switch (true) {
case i % 15 === 0:
console.log("FizzBuzz");
break;
case i % 3 === 0:
console.log("Fizz");
break;
case i % 5 === 0:
console.log("Buzz");
break;
default:
console.log(i);
break;
}
}
JavaScript (if):
for (let i = 1; i <= 100; i++) {
if (i % 3 === 0 && i % 5 === 0) {
console.log("FizzBuzz");
} else if (i % 3 === 0) {
console.log("Fizz");
} else if (i % 5 === 0) {
console.log("Buzz");
} else {
console.log(i);
}
}
Swift
for i in 1...100 {
switch i % 15 {
case 0:
print("FizzBuzz")
case 3, 6, 9, 12:
print("Fizz")
case 5, 10:
print("Buzz")
default:
print(i)
}
}
C (if):
#include <stdio.h>
/* There's no reason to care about parameters */
int main() {
for(int q=0;q<101;q++) {
/* Most common edge case first */
if(q%3==0) printf("Fizz\n");
else if(q%5==0) printf("Buzz\n");
else if(q%15==0) printf("FizzBuzz\n");
else printf("%d\n", q);
}
}
Lisp:
(defun is-multiple (i against)
(= (mod i against) 0))
(defun fizzbuzz (i)
(let ((p (concatenate 'string (if (is-multiple i 3) "Fizz" "") (if (is-multiple i 5) "Buzz" ""))))
(print (if (string= p "") i p))))
(dotimes (i 101) (fizzbuzz i))
Rust:
fn main() {
let mut count = 1;
while count < 101{
if count % 3 == 0 && count % 5 == 0{
println!("FizzBuzz");
} else if count % 3 == 0{
println!("Fizz");
} else if count % 5 == 0{
println!("Buzz");
} else{
println!("{count}");
}
count = count + 1;
}
}