Skip to content

Instantly share code, notes, and snippets.

@DataWraith
Created August 6, 2017 08:10
Show Gist options
  • Save DataWraith/cf192945c6452146ce7380c33e5224b9 to your computer and use it in GitHub Desktop.
Save DataWraith/cf192945c6452146ce7380c33e5224b9 to your computer and use it in GitHub Desktop.
Flexible FizzBuzz implementation using Streams in Elixir
defmodule FizzBuzz do
@moduledoc """
FizzBuzz outputs integers interspersed with configurable words
at configurable intervals.
"""
def fizzbuzz(count, words \\ [{3, "Fizz"}, {5, "Buzz"}]) do
words
|> Enum.map(&make_word_stream/1)
|> Stream.zip
|> Stream.with_index(1)
|> Stream.map(&format_fizzbuzz/1)
|> Stream.take(count)
|> Enum.each(& IO.puts(&1))
nil
end
defp make_word_stream({interval, word}) when interval > 0 do
# This might not be such a great idea for large intervals, but fizzbuzz intervals
# are usually on the order of 3 or 5. ;-)
Stream.cycle(Enum.into([word], List.duplicate("", interval - 1)))
end
defp format_fizzbuzz({words, index}) do
str =
words
|> Tuple.to_list
|> Enum.reduce(fn (word, acc) -> acc <> word end)
if str == "" do
index
else
str
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment