Last active
September 11, 2019 17:49
-
-
Save mvelebit/3008958b8d55783b46e1212908ae64a8 to your computer and use it in GitHub Desktop.
A (somewhat) ugly but flexible solution to the fizzbuzz problem in Elixir
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
defmodule FizzBuzz do | |
@default_map %{3 => "Fizz", 5 => "Buzz"} | |
@default_range_size 100 | |
def go() do | |
go(@default_map, @default_range_size) | |
end | |
def go(map, range_size) | |
when is_map(map) | |
and is_integer(range_size) | |
and range_size > 1 do | |
for i <- 1..range_size do | |
get_combined_or_one(map, i) | |
end | |
end | |
def go(map, range_size) do | |
raise "Invalid arguments! Check if the provided map is a map and | |
if the range is an integer greater than 1" | |
end | |
defp get_combined_or_one(map, current_i) do | |
Enum.reduce(Map.keys(map), &(&1 * &2)) | |
|> checks_out(current_i) | |
|> return_combined_or_return_one(map, current_i) | |
end | |
defp return_combined_or_return_one(should_return_combined, map, current_i) do | |
if should_return_combined do | |
IO.puts Enum.reduce(Map.values(map), &(&2 <> &1)) | |
else | |
IO.puts get_one_or_return_current(map, current_i) | |
end | |
end | |
@doc """ | |
Helper functions below | |
""" | |
defp checks_out(number, divider) do | |
rem(divider, number) == 0 | |
end | |
defp get_one_or_return_current(map, number) do | |
map | |
|> Enum.find(fn {key, _val} -> checks_out(key, number) end) | |
|> get_or_default(map, number) | |
end | |
defp get_or_default(current_pair, map, num) do | |
if current_pair do | |
Map.get(map, elem(current_pair, 0)) | |
else | |
num | |
end | |
end | |
end | |
FizzBuzz.go() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment