Avatar of PercyGrunwald

PercyGrunwald's solution

to Roman Numerals in the Elixir Track

Published at Jan 03 2019 · 0 comments
Instructions
Test suite
Solution

Write a function to convert from normal numbers to Roman Numerals.

The Romans were a clever bunch. They conquered most of Europe and ruled it for hundreds of years. They invented concrete and straight roads and even bikinis. One thing they never discovered though was the number zero. This made writing and dating extensive histories of their exploits slightly more challenging, but the system of numbers they came up with is still in use today. For example the BBC uses Roman numerals to date their programmes.

The Romans wrote numbers using letters - I, V, X, L, C, D, M. (notice these letters have lots of straight lines and are hence easy to hack into stone tablets).

 1  => I
10  => X
 7  => VII

There is no need to be able to convert numbers larger than about 3000. (The Romans themselves didn't tend to go any higher)

Wikipedia says: Modern Roman numerals ... are written by expressing each digit separately starting with the left most digit and skipping any digit with a value of zero.

To see this in practice, consider the example of 1990.

In Roman numerals 1990 is MCMXC:

1000=M 900=CM 90=XC

2008 is written as MMVIII:

2000=MM 8=VIII

See also: http://www.novaroma.org/via_romana/numbers.html

Running tests

Execute the tests with:

$ elixir roman_numerals_test.exs

Pending tests

In the test suites, all but the first test have been skipped.

Once you get a test passing, you can unskip the next one by commenting out the relevant @tag :pending with a # symbol.

For example:

# @tag :pending
test "shouting" do
  assert Bob.hey("WATCH OUT!") == "Whoa, chill out!"
end

Or, you can enable all the tests by commenting out the ExUnit.configure line in the test suite.

# ExUnit.configure exclude: :pending, trace: true

If you're stuck on something, it may help to look at some of the available resources out there where answers might be found.

Source

The Roman Numeral Kata http://codingdojo.org/cgi-bin/index.pl?KataRomanNumerals

Submitting Incomplete Solutions

It's possible to submit an incomplete solution so you can see how others have completed the exercise.

roman_numerals_test.exs

if !System.get_env("EXERCISM_TEST_EXAMPLES") do
  Code.load_file("roman.exs", __DIR__)
end

ExUnit.start()
ExUnit.configure(exclude: :pending, trace: true)

defmodule RomanTest do
  use ExUnit.Case

  # @tag :pending
  test "1" do
    assert Roman.numerals(1) == "I"
  end

  @tag :pending
  test "2" do
    assert Roman.numerals(2) == "II"
  end

  @tag :pending
  test "3" do
    assert Roman.numerals(3) == "III"
  end

  @tag :pending
  test "4" do
    assert Roman.numerals(4) == "IV"
  end

  @tag :pending
  test "5" do
    assert Roman.numerals(5) == "V"
  end

  @tag :pending
  test "6" do
    assert Roman.numerals(6) == "VI"
  end

  @tag :pending
  test "9" do
    assert Roman.numerals(9) == "IX"
  end

  @tag :pending
  test "27" do
    assert Roman.numerals(27) == "XXVII"
  end

  @tag :pending
  test "48" do
    assert Roman.numerals(48) == "XLVIII"
  end

  @tag :pending
  test "59" do
    assert Roman.numerals(59) == "LIX"
  end

  @tag :pending
  test "93" do
    assert Roman.numerals(93) == "XCIII"
  end

  @tag :pending
  test "141" do
    assert Roman.numerals(141) == "CXLI"
  end

  @tag :pending
  test "163" do
    assert Roman.numerals(163) == "CLXIII"
  end

  @tag :pending
  test "402" do
    assert Roman.numerals(402) == "CDII"
  end

  @tag :pending
  test "575" do
    assert Roman.numerals(575) == "DLXXV"
  end

  @tag :pending
  test "911" do
    assert Roman.numerals(911) == "CMXI"
  end

  @tag :pending
  test "1024" do
    assert Roman.numerals(1024) == "MXXIV"
  end

  @tag :pending
  test "3000" do
    assert Roman.numerals(3000) == "MMM"
  end
end
defmodule Roman do
  @int_to_roman_numeral_map %{
    1 => "I",
    5 => "V",
    10 => "X",
    50 => "L",
    100 => "C",
    500 => "D",
    1000 => "M"
  }

  @doc """
  Convert the number to a roman number.
  """
  @spec numerals(pos_integer) :: String.t()
  def numerals(number) do
    number
    |> split_integer()
    |> multiply_by_ten_power()
    |> Enum.reject(fn int -> int == 0 end)
    |> Enum.map(&get_combined_numbers/1)
    |> List.flatten()
    |> Enum.map(&Map.get(@int_to_roman_numeral_map, &1, ""))
    |> Enum.join()
  end

  defp split_integer(int) do
    int
    |> Kernel.to_string()
    |> String.split("", trim: true)
    |> Enum.map(fn int_string ->
      Integer.parse(int_string)
      |> case do
        {int, _} ->
          int

        _ ->
          0
      end
    end)
  end

  defp multiply_by_ten_power(int_list) do
    int_list
    |> Enum.with_index(1)
    |> Enum.map(fn {int, index} ->
      ten_factor = :math.pow(10, length(int_list) - index) |> :erlang.floor()

      int * ten_factor
    end)
  end

  defp get_combined_numbers(int, acc \\ {[], 0}) do
    is_negative? = int < 0
    abs_int = :erlang.abs(int)
    number_pool = Map.keys(@int_to_roman_numeral_map)
    {acc_list, last_index_inserted} = acc
    {difference, closest_int} = get_difference_and_closest_int(abs_int, number_pool)

    index_to_insert =
      if is_negative? do
        last_index_inserted - 1
      else
        last_index_inserted + 1
      end

    acc_list = List.insert_at(acc_list, index_to_insert, closest_int)

    if difference == 0 do
      acc_list
    else
      get_combined_numbers(difference, {acc_list, index_to_insert})
    end
  end

  defp get_difference_and_closest_int(abs_int, number_pool) do
    number_pool_with_differences =
      number_pool
      |> Enum.map(fn int_to_compare ->
        {abs_int - int_to_compare, int_to_compare}
      end)

    {{difference, closest_int}, index} =
      number_pool_with_differences
      |> Enum.with_index()
      |> Enum.min_by(fn {{difference, _int_to_compare}, _index} ->
        :erlang.abs(difference)
      end)

    cond do
      difference == 0 ->
        {difference, closest_int}

      difference > 0 ->
        {difference, closest_int}

      difference < 0 ->
        # 85 => LXXXV
        # 85 => ... ___{35, 50}___, {-15, 100} ...
        #
        # 90 => XVC
        # 90 => ... {40, 50}, ___{-10, 100}___ ...
        abs_difference = :erlang.abs(difference)

        exact_match = Enum.find(number_pool, fn number -> number == abs_difference end)

        if not is_nil(exact_match) do
          {difference, closest_int}
        else
          Enum.at(number_pool_with_differences, index - 1)
        end
    end
  end
end

Community comments

Find this solution interesting? Ask the author a question to learn more.

What can you learn from this solution?

A huge amount can be learned from reading other people’s code. This is why we wanted to give exercism users the option of making their solutions public.

Here are some questions to help you reflect on this solution and learn the most from it.

  • What compromises have been made?
  • Are there new concepts here that you could read more about to improve your understanding?