Created
November 9, 2019 21:29
-
-
Save neenjaw/22fc66fd0d6b3c6cf83610e256fbee46 to your computer and use it in GitHub Desktop.
herzrasen roman numerals
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 RomanNumerals do | |
@romans [ | |
{1000, "M"}, | |
{900, "CM"}, | |
{500, "D"}, | |
{400, "CD"}, | |
{100, "C"}, | |
{90, "XC"}, | |
{50, "L"}, | |
{40, "XL"}, | |
{10, "X"}, | |
{9, "IX"}, | |
{5, "V"}, | |
{4, "IV"}, | |
{1, "I"} | |
] | |
# @romans %{ | |
# 1 => "I", | |
# 4 => "IV", | |
# 5 => "V", | |
# 9 => "IX", | |
# 10 => "X", | |
# 40 => "XL", | |
# 50 => "L", | |
# 90 => "XC", | |
# 100 => "C", | |
# 400 => "CD", | |
# 500 => "D", | |
# 900 => "CM", | |
# 1000 => "M" | |
# } | |
@doc """ | |
Convert the number to a roman number. | |
""" | |
@spec numeral(pos_integer) :: String.t() | |
def numeral(number) do | |
{0, digits} = to_roman(number, "") | |
digits | |
# |> to_string() | |
end | |
defp to_roman(0, digits), do: {0, digits} | |
defp to_roman(number, digits) do | |
# closest = closest_roman(number) | |
{closest, numeral} = | |
Enum.find(@romans, fn {value, _numeral} -> | |
number >= value | |
end) | |
to_roman(number - closest, digits <> numeral) | |
end | |
# defp closest_roman(number) do | |
# Map.keys(@romans) | |
# |> Enum.filter(&smaller_or_equal?(number, &1)) | |
# |> Enum.min_by(&diff_between(number, &1)) | |
# end | |
# defp smaller_or_equal?(n, m), do: n >= m | |
# defp diff_between(n, m), do: n - m | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment