Created
April 19, 2015 18:14
-
-
Save janxious/c66058b9108343a3bc0d to your computer and use it in GitHub Desktop.
Elixir: 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 RomanNumeral do | |
@numerals [ | |
{50, "L"}, | |
{40, "XL"}, | |
{10, "X"}, | |
{9, "IX"}, | |
{5, "V"}, | |
{4, "IV"}, | |
{1, "I"} | |
] | |
def convert(number) do | |
convert(number, @numerals) | |
end | |
defp convert(0, _numerals), do: "" | |
defp convert(number, [{arabic, roman} | tail]) when number >= arabic do | |
roman <> convert(number - arabic, [{arabic, roman} | tail]) | |
end | |
defp convert(number, [{arabic, _roman} | tail]) when number < arabic do | |
convert(number, tail) | |
end | |
end |
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 RomanNumeralTest do | |
use ExUnit.Case | |
test "converts arabic numbers into roman numerals" do | |
numeric_mapping = [ | |
{0, ""}, | |
{1, "I"}, | |
{2, "II"}, | |
{3, "III"}, | |
{4, "IV"}, | |
{5, "V"}, | |
{6, "VI"}, | |
{9, "IX"}, | |
{10, "X"}, | |
{19, "XIX"}, | |
{20, "XX"}, | |
{28, "XXVIII"}, | |
{40, "XL"}, | |
{49, "XLIX"}, | |
{50, "L"}, | |
] | |
Enum.each(numeric_mapping, fn({arabic, roman}) -> assert RomanNumeral.convert(arabic) == roman end) | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment