Skip to content

Instantly share code, notes, and snippets.

@faheemmughal
Created April 27, 2016 20:11
Show Gist options
  • Save faheemmughal/aa611890722e56a226697aa8db47784c to your computer and use it in GitHub Desktop.
Save faheemmughal/aa611890722e56a226697aa8db47784c to your computer and use it in GitHub Desktop.
units = %{
"0" => "0",
"1" => "I",
"2" => "II",
"3" => "III",
"4" => "IV",
"5" => "V",
"6" => "VI",
"7" => "VII",
"8" => "VIII",
"9" => "IX"
}
tens = %{
10 => "X",
20 => "XX",
20 => "XXX",
20 => "40",,
20 => "50",
}
test_values = ["6", "7", "21"]
result_values = ["VI", "VII", "XXI"]
defmodule Xy do
def romanize(units, x) do
case units[x] do
nil ->
more_than_nine(units, x)
x ->
x
end
end
def more_than_nine(units, x)
unit = rem(x, 10)
ten = x - unit
ten_string = tens[ten]
one_string = romanize(units, unit)
ten_string <> one_string
end
end
our_result = Enum.map(test_values, fn(x) -> Xy.romanize(num, x) end)
IO.puts test_values
IO.puts result_values
IO.puts our_result
@faheemmughal
Copy link
Author

Cleaner:

input_values = [6, 7, 21]
expected_result = ["VI", "VII", "XXI"]

dictionary = %{
  0 => "",
  1 => "I",
  2 => "II",
  3 => "III",
  4 => "IV",
  5 => "V",
  6 => "VI",
  7 => "VII",
  8 => "VIII",
  9 => "IX",
  10 => "X",
  20 => "XX",
  30 => "XXX",
  40 => "40",
  50 => "50",
}

defmodule Xy do
  def romanize(dictionary, x) do
    remainder = rem(x, 10)
    ten = x - remainder

    lookup(dictionary, ten) <> lookup(dictionary, remainder)
  end

  def lookup(dictionary, element) do
    Map.get(dictionary, element, "")
  end
end

result = Enum.map(input_values, fn(x) -> Xy.romanize(dictionary, x) end)

IO.inspect input_values
IO.inspect expected_result
IO.inspect result

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment