[Algorithm] Solving FizzBuzz in Three Ways

Aaron Lu
3 min readMay 26, 2019

--

Target

Write 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”.

  1. Print out numbers 1 to 100
  2. Replace all numbers divisible by 3 with “Fizz”
  3. Replace all numbers divisible by 5 with “Buzz”
  4. replace all numbers divisible by both 3 and 5 with “FizzBuzz”

Solution 1 — Intuitive Approach

Using for loop & if … else … statement

for (var i = 1; i <= 100; i++) {
if (i % 15 === 0) console.log("FizzBuzz");
else if (i % 3 === 0) console.log("Fizz");
else if (i % 5 === 0) console.log("Buzz");
else console.log(i);
}

Solution 2 — String Concatenation

Instead of hardcoding the multiple of 15, we used variable here to concatenate the corresponding string.

for (var i = 1; i <= 100; i++) {
let answer = '';
if (i % 3 === 0) answer += "Fizz";
if (i % 5 === 0) answer += "Buzz";
if (!answer) answer = i;
console.log(answer);
}

Solution 3 — Hash all the conditions (Best)

First of all, we store all the conditions in Object.
Then, iterating all of them (both key and value) through Object.entries.
So that we can easily separate our conditions and codes.

map & join

const condition = { 3: "Fizz", 5: "Buzz" };for (var i = 1; i <= 100; i++) {
let answer = Object.entries(condition)
.map(([key, value]) => i % key === 0 ? value : "")
.join("");
if (!answer) answer = i;
console.log(answer);
}

reduce

const condition = { 3: "Fizz", 5: "Buzz" };for (var i = 1; i <= 100; i++) {
let answer = Object.entries(condition)
.reduce((acc, [key, value]) => acc += i % key === 0 ? value : "", "");
if (!answer) answer = i;
console.log(answer);
}

filter & forEach

Changing map & join to filter & forEach plays the same role here.

const condition = { 3: "Fizz", 5: "Buzz" };for (var i = 1; i <= 100; i++) {
let answer = "";
Object.entries(condition)
.filter(([key]) => i % key === 0)
.forEach(([key, value]) => answer += value);
if (!answer) answer = i;
console.log(answer);
}

Performance Test

3 Solutions
Third Solution

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

--

--

Aaron Lu
Aaron Lu

Written by Aaron Lu

Software Engineer with experience in languages such as HTML5, CSS3, JavaScript, Node.js and MySQL, frameworks such as React, React-Native, express and Nest.js

Responses (1)

Write a response