Tuesday 24 January 2017

Fizzbuzz

I had the pleasure of interviewing a few people today1. I always learn a tonne from watching how people approach a simple problem. It is quite revealing.

When we interview people at SoPost, one of the things we have people do is write an implementation of FizzBuzz.

I saw two new FizzBuzz’s that I had not seen before.

defmodule Interview do
 
  # mmm guards
  defp fizzbuzz1(x) when rem(x, 5) == 0 and rem(x, 3) == 0, do: "FizzBuzz"
  defp fizzbuzz1(x) when rem(x, 3) == 0, do: "Fizz"
  defp fizzbuzz1(x) when rem(x, 5) == 0, do: "Buzz"
  defp fizzbuzz1(x), do: x  
  
  def fizzbuzz1 do
    Enum.map(1..30, &(fizzbuzz1/1))
  end
  
  # pattern match me up
  defp fizzbuzz2(x) do
    case {rem(x, 3), rem(x, 5)} do
        {0, 0} ->
        "FizzBuzz"
      {0, _} ->
        "Fizz"
      {_, 0} ->
        "Buzz"
       _ ->
        x
    end
  end

  def fizzbuzz2 do
    Enum.map(1..30, &(fizzbuzz2/1))
  end
end

Always nice to broaden your horizon. Here was one I prepared earlier.

defmodule Foo do
  def fizzbuzz(range) do
    Enum.map(range, fn x ->
      cond do
        rem(x, 5) == 0 && rem(x, 3) == 0 ->
            IO.puts "FizzBuzz"
        rem(x, 5) == 0 ->
            IO.puts "Buzz"
        rem(x, 3) == 0 ->
            IO.puts "Fizz"
        true ->
            IO.puts x
       end
      end)
    end
  end


Foo.fizzbuzz(1..30)

Edit: 6th Feb - After considering pure functions I arrived at this implementation, that unlike the above, has no side effects.

Enum.map(1..30, fn(x) ->
  case {rem(x, 3), rem(x, 5)} do
      {0, 0} ->
        "FizzBuzz"
      {0, _} ->
        "Fizz"
      {_, 0} ->
        "Buzz"
      _->
        x
  end
end)
|> Enum.join("\n")
|> IO.puts

By the way, if you’ve been Googling around ahead of a SoPost interview and you crack out one of these, I may quiz you about your source.


  1. A topic that deserves it’s own post. But suffice to say is inspired a lot by something Mr Ozuman put together when he was at SoPost. Miss you.