Created
January 5, 2017 13:07
-
-
Save fjunior87/8d333b5852b7b4e8524aea0350ff0321 to your computer and use it in GitHub Desktop.
This file contains hidden or 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 | |
@vals %{ | |
"I" => 1, | |
"V" => 5, | |
"X" => 10, | |
"L" => 50, | |
"C" => 100, | |
"D" => 500, | |
"M" => 1000 | |
} | |
def to_arabic(roman_numeral) do | |
convert(String.graphemes(roman_numeral)) | |
end | |
def convert([]) do | |
0 | |
end | |
def convert([h1, h2|tail]) do | |
num1 = val(h1) | |
num2 = val(h2) | |
num1 = | |
cond do | |
num2 > num1 -> | |
num1 * -1 | |
true -> | |
num1 | |
end | |
num1 + num2 + convert(tail) | |
end | |
def convert([h1|tail]) do | |
val(h1) + convert(tail) | |
end | |
defp val(letter) do | |
@vals[letter] | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment