DEV Community 👩‍💻👨‍💻

Jeremy Grifski
Jeremy Grifski

Posted on

Fizz Buzz in Every Language

I noticed some folks on here were sharing some coding challenges, and I thought it might be fun to share some of my own (and shamelessly promote my Sample Programs project in the process).

The Challenge

Fizz Buzz is that notorious interview question almost everyone in the industry knows. Ironically, I don't know of anyone who has every been asked it. Regardless, it's a fun problem to tackle because it involves a little bit of everything: loops, conditions, math, etc. And, there are countless ways to solve it.

For the purposes of this challenge, here are the rules:

Write a program that prints the numbers 1 to 100. However, for multiples of three, print “Fizz” instead of the number. Meanwhile, for multiples of five, print “Buzz” instead of the number. For numbers which are multiples of both three and five, print “FizzBuzz”

Here's a segment of the output:

1
2
Fizz
4
Buzz
Fizz
7
8
Fizz
Buzz
11
Fizz
13
14
FizzBuzz
Enter fullscreen mode Exit fullscreen mode

If you're feeling festive, you can swap the terms for whatever you like (i.e. EasterEgg, AprilShowers, etc.). In any case, the solution should be executable in any language of your choice. The more obscure the language, the better!

The Solution

I'll kick off the challenge with my favorite solution to the problem in Java:

public class FizzBuzz {
  public static void main(String[] args) {
    for (int i = 1; i < 101; i++) {
      String output = "";
      if (i % 3 == 0) {
        output += "Fizz";
      }
      if (i % 5 == 0) {
        output += "Buzz";
      }
      if (output.isEmpty()) {
        output += i;
      }
      System.out.println(output);
    }
  }
}
Enter fullscreen mode Exit fullscreen mode

If you're curious how this solution works, Stuart Irwin wrote an excellent article about it. Along with this solution, I've been collecting several others in a repo called Sample Programs. After you drop your solution below, you should see if its missing from the collection. We'd love your contribution!

Top comments (38)

Collapse
 
stephanie profile image
Stephanie Handsteiner

CSS

ol {
   list-style-type: inside;
}

li:nth-child(3n), li:nth-child(5n) {
   list-style-type: none;
}

li:nth-child(3n):before {
   content: 'Fizz';
}

li:nth-child(5n):after {
   content: 'Buzz';
}
Enter fullscreen mode Exit fullscreen mode
Collapse
 
renegadecoder94 profile image
Jeremy Grifski

Haha I love that you can do this in CSS.

Collapse
 
bruxisma profile image
Isabella Muerte

There's several ways to do it in C++ :)

The Classic

#include <cstdio>
int main () {
  for (auto i = 1; i < 101; ++i) {
    if (i % 3 == 0) { std::printf("Fizz"); }
    if (i % 5 == 0) { std::printf("Buzz"); }
    std::printf(" %d\n", i);
  }
}
Enter fullscreen mode Exit fullscreen mode

The "GOSH, MOM, IT'S GENERIC"

#include <cstdio>

struct number {
  number (int x) : x(x) { }
  auto operator * () const { return this->x; }
  bool operator == (int y) { return this->x == y; }
  bool operator != (int y) { return this->x != y; }
  number& operator ++ () { ++this->x; return *this; }
  number operator ++ (int) { return this->x++; }
  int x;
};


struct range {
    range (int start, int stop) :
      start(start),
      stop(stop)
    { }

    auto begin () const { return number(this->start); }
    auto end () const { return this->stop; }
private:
  int start;
  int stop;
};



int main () {
  for (auto i : range(1, 101)) {
    if (i % 3 == 0) { std::printf("Fizz"); }
    if (i % 5 == 0) { std::printf("Buzz"); }
    std::printf(" %d\n", i);
  }
}
Enter fullscreen mode Exit fullscreen mode

The "Calculated At Compile Time (stare into madness edition)"

#include <type_traits>
#include <utility>
#include <cstdio>

template <char... Args>
struct as_string { const char data[sizeof... (Args)] = { Args... }; };

using fizz = as_string<'f', 'i', 'z', 'z'>;
using buzz = as_string<'b', 'u', 'z', 'z'>;
using newline = as_string<'\n'>;
using null = as_string<'\0'>;
struct fizzbuzz: fizz, buzz { };

template <class T> struct type_identity { using type = T; };

template <class T>
constexpr auto digits (T x) {
    auto digits = 0;
    while (x) {
        x /= 10;
        digits++;
    }
    return digits;
}

template <auto Size, auto X, char... Args>
struct to_string : to_string<Size - 1, X / 10, '0' + X % 10, Args...> { };

template <auto X, char... Args>
struct to_string<1, X, Args...> : type_identity<as_string<'0' + X, Args...>> { };

template <unsigned int X>
using int_to_string = typename to_string<digits(X), X>::type;

template <auto X, class Fizzable = std::bool_constant<X % 3 == 0>, class Buzzable = std::bool_constant<X % 5 == 0>> struct check;

template <auto X> struct check<X, std::false_type, std::false_type> : int_to_string<X> { };
template <auto X> struct check<X, std::true_type, std::false_type> : fizz, int_to_string<X> { };
template <auto X> struct check<X, std::false_type, std::true_type> : buzz, int_to_string<X> { };
template <auto X> struct check<X, std::true_type, std::true_type> : fizzbuzz, int_to_string<X> { };

template <auto X> struct calc : check<X>, newline { };
template <auto... X> struct print : calc<X>..., null { };

template <auto... Is>
print<(Is + 1)...> deduce (std::index_sequence<Is...>);

template <auto N>
using result = decltype(deduce(std::make_index_sequence<N>()));

static constexpr result<100> fb{};

int main() {
    std::puts(reinterpret_cast<const char *>(&fb));
    return 0;
}
Enter fullscreen mode Exit fullscreen mode
Collapse
 
nepeckman profile image
nepeckman

I raise you the compile time calculated fizzbuzz in Nim ;)

proc fizzbuzz(): seq[string] =
  result = @[]
  for i in 1..100:
    result.add(
      if i mod 15 == 0: "FizzBuzz"
      elif i mod 5 == 0: "Buzz"
      elif i mod 3 == 0: "Fizz"
      else: $i
    )

const compileTimeValue = fizzbuzz()

echo compileTimeValue
Collapse
 
bruxisma profile image
Isabella Muerte

C++20 isn't available yet, but we're a bit closer to this approach. :)

Collapse
 
renegadecoder94 profile image
Jeremy Grifski

Interested in adding this to the collection? 😁

Collapse
 
renegadecoder94 profile image
Jeremy Grifski

That last one scares me. Haha I’m not sure I’d know where to start reading it.

Thanks for jumping into the challenge with some great additions. 😃

Collapse
 
theodesp profile image
Theofanis Despoudis
Collapse
 
cjbrooks12 profile image
Casey Brooks • Edited on

number 3 is the Cthulu of FizzBuzz

Collapse
 
tlackiesapidyne profile image
Terrance Lackie

These actually fail the FizzBuzz challenge because they print numbers that are divisible by 3 and/or 5. The challenge specifically states to print Fizz, Buzz, or FizzBuzz INSTEAD of the number.

Collapse
 
avalander profile image
Avalander • Edited on

Here's my implementation in Racket

(define (mult-15? n)
  (and (mult-5? n)
       (mult-3? n)))

(define (mult-5? n)
  (= (modulo n 5) 0))

(define (mult-3? n)
  (= (modulo n 3) 0))

(define (fizzbuzz n)
  (cond
    [(mult-15? n) "FizzBuzz"]
    [(mult-5? n) "Buzz"]
    [(mult-3? n) "Fizz"]
    [else n]))

(define (print-list xs)
  (map displayln xs))

(print-list (map fizzbuzz (range 1 101)))

The print-list function is a bit redundant, since (map fizzbuzz (range 1 101)) will already print the resulting list to the console.

Collapse
 
gypsydave5 profile image
David Wickes

Ah come on @avalander - surely you should've written a FizzBuzz DSL in Racket? 😉

Collapse
 
avalander profile image
Avalander

I should, but I don't know enough Racket for that yet 😅

Collapse
 
renegadecoder94 profile image
Jeremy Grifski

Great stuff! I like racket a lot, but I haven't written any code in it myself. The fact that there are so many dialects of it is pretty cool to me.

Collapse
 
avalander profile image
Avalander

Thanks! I've just started learning it myself. I can recommend the book Realm of Racket if you want to give it a shot.

Collapse
 
steveyeadon profile image
Stephen Yeadon

Sql anybody?

DECLARE @i INT = 100;

;WITH E1(N) AS (SELECT 1 UNION ALL SELECT 1 UNION ALL SELECT 1 UNION ALL 
                SELECT 1 UNION ALL SELECT 1 UNION ALL SELECT 1 UNION ALL 
                SELECT 1 UNION ALL SELECT 1 UNION ALL SELECT 1 UNION ALL SELECT 1), -- 1*10^1 or 10 rows
      E2(N) AS (SELECT 1 FROM E1 a, E1 b),                                          -- 1*10^2 or 100 rows
      E4(N) AS (SELECT 1 FROM E2 a, E2 b),                                          -- 1*10^4 or 10,000 rows
      E8(N) AS (SELECT 1 FROM E4 a, E4 b),                                          -- 1*10^8 or 100,000,000 rows
cteTally(N) AS (SELECT TOP (@i) ROW_NUMBER() OVER (ORDER BY (SELECT NULL)) FROM E8)

SELECT  CASE WHEN N % 15 = 0 THEN 'fizzbuzz'
             WHEN N % 5 = 0 THEN 'buzz'
             WHEN N % 3 = 0 THEN 'fizz'  
             ELSE CONVERT(VARCHAR(10),N) END
FROM    cteTally


`

Collapse
 
nssimeonov profile image
Templar++

Because using a cursor is too mainstream? :)

Collapse
 
avalander profile image
Avalander

Since nobody has done Javascript yet, here's a crazy implementation.

const worder = (predicate, patterner) => (prev, n) =>
  predicate(prev, n)
    ? patterner(prev, n)
    : prev

const isDivisible = d => (_, n) =>
  n % d === 0

const isEmpty = s =>
  s.length === 0

const append = x => (prev) => prev + x

const setNumber = (_, n) => n

const fizzer = worder(isDivisible(3), append('fizz'))

const buzzer = worder(isDivisible(5), append('buzz'))

const numberer = worder(isEmpty, setNumber)

const reducer = (...worders) => n =>
  worders.reduce(
    (prev, w) => w(prev, n),
    ''
  )

const fizzbuzzer = reducer(
  fizzer,
  buzzer,
  numberer
)

for (let i = 0; i <= 100; i++) {
  console.log(fizzbuzzer(i))
}

Consider how easy it is to extend to print 'fazz' for multiples of 7.

const fazzer = worder(isDivisible(7), append('fazz'))

const fizzbuzzfazzer = reducer(
  fizzer,
  buzzer,
  fazzer,
  numberer
)
Collapse
 
renegadecoder94 profile image
Jeremy Grifski

I appreciate the commitment to the obscure. Haha these are great.

Collapse
 
avalander profile image
Avalander

That's the whole point of the exercise, right? :D

Thread Thread
 
renegadecoder94 profile image
Jeremy Grifski

Oh absolutely! Got any code golf solutions?

Thread Thread
 
avalander profile image
Avalander • Edited on

Hmm... the best I can come up with right now is 85 chars. Nothing really clever, just sacrificed readability for space.

let i=0;while(i++<101){console.log(i%15==0?'fizzbuzz':i%5==0?'buzz':i%3==0?'fizz':i)}

Another fun one, albeit longer, is this.

console.log(new Array(101)
  .fill(1)
  .map((_, i) =>
    i % 15 == 0 ? 'fizzbuzz' :
    i % 3 == 0 ? 'fizz' :
    i % 5 == 0 ? 'buzz' :
    i
  )
  .slice(1)
  .join('\n'))
Collapse
 
nielsbom profile image
Niels Bom

Elixir

1..100
|> Enum.map(fn
  n when rem(n, 3) == 0 and rem(n, 5) == 0 -> "FizzBuzz"
  n when rem(n, 3) == 0 -> "Fizz"
  n when rem(n, 5) == 0 -> "Buzz"
  n -> Integer.to_string(n)
end)
|> Enum.each(&IO.puts/1)
Collapse
 
bjorngrunde profile image
Björn Grunde

Here is another example using as a Module and using pattern matching. It looks hilarious :P

defmodule FizzBuzz do

  def run(num) when num >= 1 and num <= 100 do:
    fizzbuzz(num, rem(n, 3), rem(n, 5))
    run(num - 1)
  end

  def run(0), do: {:ok, "Done"}
  def run(_) do: {:error, "Something went wrong"}

  defp fizzbuzz(_, 0, 0), do: IO.puts "Fizzbuzz"
  defp fizzbuzz(_, 0, _), do: IO.puts "Fizz"
  defp fizzbuzz(_, _, 0), do: IO.puts "Buzz"
  defp fizzbuzz(n, _, _), do: n |> to_string |> IO.puts
end

# Example
FizzBuzz.run(55)
Collapse
 
renegadecoder94 profile image
Jeremy Grifski

Ooh, this would make a nice addition to the repo.

Collapse
 
nielsbom profile image
Niels Bom

Go ahead.

Collapse
 
alexphi profile image
Alejandro Figueroa • Edited on

Didn't see a C# solution, so here's mine (with some linq love):

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace FizzBuzz
{
    static class Program
    {
        static void Main(string[] args)
        {
            var buzzMap = new Dictionary<int, string>
            {
                { 3, "Fizz" },
                { 5, "Buzz" },
            };

            Func<int, string> buzzer = i =>
            {
                var buzzed = buzzMap.Keys
                    .Where(k => i % k == 0)
                    .Select(k => buzzMap[k]);

                return buzzed.Any() ? buzzed.Aggregate((prev, next) => prev += next) : null;
            };

            var output = Enumerable.Range(1, 100)
                .Select(i => buzzer(i) ?? i.ToString())
                .Aggregate(new StringBuilder(), (sb, s) => sb.AppendLine(s))
                .ToString();

            Console.WriteLine(output);
        }
    }
}
Collapse
 
gypsydave5 profile image
David Wickes

Here's some fun from the world of Common Lisp

Inoffensive version

(defun divides (divisor dividend)
  (= (mod divisor dividend) 0))

(defun fizzbuzz (n)
  (let ((fizz (when (divides n 3) "Fizz"))
        (buzz (when (divides n 5) "Buzz")))
    (if (or fizz buzz)
        (concatenate 'string fizz buzz)
        (write-to-string n))))

Offensive FizzBuzz Builder Macro

For when you want to define your own custom fizzbuzzer. Nice and easy to extend.

(defun divides (divisor dividend)
  (= (mod divisor dividend) 0))

(defmacro define-fizzbuzzer (name &body pairs)
  `(defun ,name (n)
     (let ((result nil))
       (dolist (p ',pairs)
         (let ((test-passed? (if (typep (first p) 'integer)
                                 (divides n (first p))
                                 (funcall (eval (first p)) n))))
           (when test-passed? (push (second p) result))))
       (if (null result)
           (write-to-string n)
           (apply #'concatenate 'string (nreverse result))))))

(define-fizzbuzzer fizz-buzz
  (3 "Fizz")
  (5 "Buzz"))

(define-fizzbuzzer fizz-buzz-bazz
  (3 "Fizz")
  (5 "Buzz")
  (7 "Bazz"))

Most Offensive Macrogeddon Too Hot for TV Version

For when you want to define your own custom matcher logic for each word in your custom fizzbuzzer. Still lets you put a single number in for 'divides by' logic.

(defmacro define-fizzbuzzer (name &body pairs)
  (let ((ps (clean-args pairs)))
    `(defun ,name (n)
       (let ((result nil))
         (dolist (p ',ps)
           (let ((test-passed? (funcall (eval (first p)) n)))
             (when test-passed? (push (second p) result))))
         (if (null result)
             (write-to-string n)
             (apply #'concatenate 'string (nreverse result)))))))

(defun clean-args (pairs)
  (mapcar #'clean-pair pairs))

(defun clean-pair (pair)
  (cond ((typep (first pair) 'integer)
         (list '#'(lambda (n) (divides n (first pair))) (second pair)))
        ((eq (caar pair) 'function)
         pair)
        (t (error "first element of pair must be either an integer or a function"))))

(defun prime? (n)
  "evaluates to t when n is prime. Highly inefficient"
  (loop for x from 2 to (round n 2) never (divides n x)))

(defun has-a-nine-in-it? (n)
 "does the decimal representation of this number have a 9 in it?"
 (some #'(lambda (c) (char= c #\9)) (write-to-string n)))

(define-fizzbuzzer fizz-buzz
  (3 "Fizz")
  (5 "Buzz"))

(define-fizzbuzzer fazz-bazz
  (#'prime? "Fazz")
  (#'has-a-nine-in-it? "Bazz"))
Collapse
 
renegadecoder94 profile image
Jeremy Grifski

Bring on the parentheses!

Collapse
 
neiby profile image
John Neiberger

Here's a shot at an Erlang version, but I barely know Erlang.


-module(fizzbuzz).
-export([start/0]).

fizzbuzz(X) when X rem 3 == 0, X rem 5 /= 0 ->
    fizz;
fizzbuzz(X) when X rem 5 == 0, X rem 3 /= 0 ->
    buzz;
fizzbuzz(X) when X rem 3 == 0, X rem 5 == 0 ->
    fizzbuzz;
fizzbuzz(X) ->
    X.

start() ->
    Result = [fizzbuzz(X) || X <- lists:seq(1,100)],
    Result.
Enter fullscreen mode Exit fullscreen mode
Collapse
 
creativecaver profile image
Creative Cave • Edited on
    print('\n'.join(['FizzBuzz' if x % 15 == 0 else 'Fizz' if x % 3 == 0 else 'Buzz' if x % 5 == 0 else str(x) for x in range(1,101)]))

Collapse
 
renegadecoder94 profile image
Jeremy Grifski • Edited on

Is this a Python solution using a massive list comprehension?! I like it.

Collapse
 
cecilelebleu profile image
Cécile Lebleu

I know this must be very basic, but it's the first time I'm ever doing this.
Here's my implementation using JavaScript, printed into an HTML element :D

<p id="target"></p>
let target = document.getElementById("target");

for(let i = 1; i <= 100; i++) {
  if( i % 5 == 0 && i % 3 == 0 ) {
    target.innerHTML += "FizzBuzz<br>";
  } else if( i % 5 == 0 ) {
    target.innerHTML += "Fizz<br>";
  } else if( i % 3 == 0) {
    target.innerHTML += "Buzz<br>";
  } else {
    target.innerHTML += i + "<br>";
  }
}
Collapse
 
heraldofsolace profile image
Aniket Bhattacharyea

Here's APL.

{(‘FizzBuzz’ ‘Fizz’ ‘Buzz’,⍵)[(0=15 3 5|⍵)⍳1]}¨⍳100

To understand how it works, read this

Collapse
 
renegadecoder94 profile image
Jeremy Grifski

Love it! Short and sweet. I haven't gotten around to learning any APL, and the repo shows it.

Collapse
 
heraldofsolace profile image
Aniket Bhattacharyea

Yep. I saw there wasn't an APL in the repo

Collapse
 
subsr97 profile image
Subramanian 😎

Here's a solution in Go.

package main

import (
    "fmt"
)

func main() {
    for num := 1; num < 101; num++ {
        if num % 3 != 0 && num % 5 != 0 {
            fmt.Println(num)
            continue
        }
        if num % 3 == 0 {
            fmt.Print("Fizz")
        }
        if num % 5 == 0 {
            fmt.Print("Buzz")
        }
        fmt.Println()
    }
}
Collapse
 
rubberduck profile image
Christopher McClellan

Rather than post my own, I’m just going to link you to the fizzbuzz tag on Code Review. I swear I’ve reviewed this one in every language, and that includes LOLCODE.

Timeless DEV post...

How to write a kickass README

Arguably the single most important piece of documentation for any open source project is the README. A good README not only informs people what the project does and who it is for but also how they use and contribute to it.

If you write a README without sufficient explanation of what your project does or how people can use it then it pretty much defeats the purpose of being open source as other developers are less likely to engage with or contribute towards it.