Roman Numerals Challenge

Coding challenge requirements:

1. Design a regular expression which matches VALID roman numerals only.
2. Create a program which converts roman numerals to arabic numbers (what we use today) and vice-versa.
3. The program should be SCALABLE, meaning that if I extend the roman numerals beyond M, you do not have to re-write your program.
4. Bonus: The program attempts to minimize the total number of lines.

My solution:

  1. Designing a regular expression for roman numerals requires truly understanding how they work.  Although some of the following roman numerals ( I, II, III, IV, V, VI, VII, VIII, IX ) have the I positioned BEFORE the larger V or X, you will never see a I occur before a larger figure. This leads us to realize that roman numerals are a base 10 number system that can be partitioned into their place values.

    MCDXXXII

    for example is just

    M CD XXX II

    in disguise.

  2. Therefore the regular expression can deal with each place one at a time. To convert to roman numerals, we look at each digit and its place.  The function roman_one_place assigns the proper roman numerals for that place.  Values above 3 require a $heavy, a larger numeral (that is, IV, V, VI, VII, VIII, and IX all have something heavier than I in them).  Values 4 and 9 specifically require that the I is BEFORE the $heavy.  I determine what the heavy should be (line 13), and then put the I’s before or after the heavy using mod 5 and mod 4 operations as a detector (line 15. A friend suggested this implementation.).  The code is extremely dense so I suggest reading through it slowly.
  3. The program is written in full generality, using $#ones for the last index of the ONES array, $ones[-1] for the last element of the ONES array, and $place to grab the individual elements from the ONES and FIVES arrays.  The result is that extending the roman numerals requires merely adding more elements to the ONES and FIVES arrays.
  4. The roman_one_place is quite clever to deal with the $heavy in a brief but effective manner.  To convert a roman numeral to arabic, we take advantage of the fact that order doesn’t matter unless a ONES element is immediately before a directly superior ONES of FIVES element.  In that case, we must subtract its value.  Otherwise, we add its value.  Although the code should be short, of course it is good practice to comment the code, and some lines are added for terminal coloring and display.

You can view the code below.

Leave a Reply