Skip to content

Instantly share code, notes, and snippets.

@cdinger
Created July 1, 2016 21:24
Show Gist options
  • Save cdinger/9b6ac68c090fb2299afd1997061cfa56 to your computer and use it in GitHub Desktop.
Save cdinger/9b6ac68c090fb2299afd1997061cfa56 to your computer and use it in GitHub Desktop.
defmodule Roman do
@numerals %{1 => "I",
5 => "V",
10 => "X",
50 => "L",
100 => "C",
500 => "D",
1000 => "M"}
def numerals(number) do
Integer.digits(number)
|> Enum.reverse
|> Stream.with_index
|> Enum.map(&numerals_for_digit/1)
|> Enum.reverse
|> Enum.join
end
def magnitude(decimal_place) do
:math.pow(10, decimal_place) |> round
end
def numerals_for_digit(digit_with_index) do
{digit, index} = digit_with_index
magnitude = magnitude(index)
template(digit, @numerals[1 * magnitude],
@numerals[5 * magnitude],
@numerals[10 * magnitude])
end
def template(digit, one, five, ten) do
case digit do
1 -> one
2 -> one <> one
3 -> one <> one <> one
4 -> one <> five
5 -> five
6 -> five <> one
7 -> five <> one <> one
8 -> five <> one <> one <> one
9 -> one <> ten
_ -> ""
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment