Challenge: Roman numerals, both ways
Arjun is visiting a museum in Port Louis. The old clock on the wall shows IV and IX, a foundation stone says MDCCCLXIV, and the film in the cinema room ends with MMXXVI. He wants a little program to translate.
Roman numerals use seven symbols:
| Symbol | I | V | X | L | C | D | M |
|---|---|---|---|---|---|---|---|
| Value | 1 | 5 | 10 | 50 | 100 | 500 | 1000 |
Symbols are written from biggest to smallest and added up: MMXXVI is 1000 + 1000 + 10 + 10 + 5 + 1 = 2026.
The twist: a symbol is never repeated four times. Instead, a smaller symbol before a bigger one is subtracted. There are exactly six of these pairs:
| IV | IX | XL | XC | CD | CM |
|---|---|---|---|---|---|
| 4 | 9 | 40 | 90 | 400 | 900 |
So 1994 is M + CM + XC + IV = MCMXCIV.
Your task
Write two functions:
toRoman(n)turns a whole number from 1 to 3999 into Roman numerals.fromRoman(text)turns valid Roman numerals back into a number.
toRoman(2026) // "MMXXVI"
toRoman(1994) // "MCMXCIV"
toRoman(4) // "IV"
fromRoman("XIV") // 14
fromRoman("MCMXCIV") // 1994
Rules
toRomanonly gets whole numbers from 1 to 3999.fromRomanonly gets valid numerals in capital letters, so you do not need to check for mistakes.fromRoman(toRoman(n))must give backnfor every number from 1 to 3999.
Tips
- For
toRoman, make a list of 13 value/symbol pairs from biggest to smallest, with the six subtractive pairs in their places:[[1000, "M"], [900, "CM"], [500, "D"], [400, "CD"], ...]. Then take away the biggest value that fits, again and again. - For
fromRoman, an object like{ I: 1, V: 5, X: 10, ... }gives each symbol's value. Look at each symbol together with the next one: if the next is bigger, subtract this one, otherwise add it. text[i + 1]isundefinedpast the end of the string, so check thati + 1 < text.lengthfirst.