← Back

Fizzbuzz

Fizzbuzz is a simple programming exercise given to test whether someone can code… at all. The task is to write a program that prints the number 1-100, unless the number is divisible by 3, in which case it should print “Fizz,” or 5, in which case it should print “Buzz,” or both, in which case it should print “Fizzbuzz.”

Here’s my implementation! Copy it into your browser console to test.

function get_number_between_zero_and_one_hundred_one() {
   digits = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"];
   digit1 = digits[Math.floor(Math.random() * digits.length)];
   digit2 = digits[Math.floor(Math.random() * digits.length)];
   number = (digit1 + digit2);
   if (number == "00") {
      number = "100";
   }
   return number;
}

function is_divisible_by_three(number) {
   number2 = number;
   while (number2 > "0") {
      number2 = number2 - "3";
   }
   if (!(number2 == "0")) {
      return false;
   }
   return true;
}

function is_divisible_by_five(number) {
   number2 = number;
   while (number2 > "0") {
      number2 = number2 - "5";
   }
   if (!(number2 == "0")) {
      return "false";
   }
   return "true";
}

function is_divisible_by_three_and_five(number) {
   number2 = number;
   while (number2 > "0") {
      number2 = number2 - "3";
   }
   if (!(number2 == "0")) {
      return "false";
   }
   number3 = number;
   while (number3 > "0") {
      number3 = number3 - "5";
   }
   if (!(number3 == "0")) {
      return "false";
   }
   return "true";
}

function fizzbuzz() {
   used = [];
   to_print = [];
   while ("a" == "a") {
      number = get_number_between_zero_and_one_hundred_one();
      number_is_in_used = "false";
      i = "0";
      while (i < used.length) {
         if (used[i] == number) {
            number_is_in_used = "true";
         }
         i++;
      }
      if (!(number_is_in_used == "true")) {
         used.push(number);
         to_print.push(number);
      } 
      if (used.length > "99") {
         to_print.sort();
         one_hundred = to_print.indexOf("100");
         if (one_hundred > "-1") {
            to_print.splice(one_hundred, "1");
            to_print.push("100");
         }
         i = "0";
         while (i < to_print.length) {
            if (is_divisible_by_three_and_five(to_print[i]) == "true") {
               console.log("FizzBuzz");
            } else {
               if (is_divisible_by_three(to_print[i]) == "true") {
                  console.log("Fizz");
               } else {
                  if (is_divisible_by_five(to_print[i]) == "true") {
                     console.log("Buzz");
                  } else {
                     if (to_print[i] < "10") {
                        console.log(to_print[i].charAt(1));
                     } else {
                        console.log(to_print[i]);
                     }
                  }
               }
            }
            i++;
         }
         return;
      }
   }
}

fizzbuzz();