# Scala algorithm: Compute a Roman numeral for an Integer, and vice-versa

Published

## Algorithm goal

Roman numerals originated from the Etruscan numerals system, which inspired the Roman numeral symbols:

Table of Roman numeral symbols
73868876676877
1510501005001000

In this system, 1 is 'I', 8 is 'VIII', 4 is 'IV', 199 is 'CXCIX' ($$100 + (90 + 9)$$).

Our goal is to convert between this representation and our Arabic numerical representation. Since the Roman numeral system is limited, going above 5000 is note necessary.

## Test cases in Scala

assert(romanNumeral(1) == "I")
assert(romanNumeral(8) == "VIII")
assert(romanNumeral(39) == "XXXIX")
assert(romanNumeral(246) == "CCXLVI")
assert(romanNumeral(789) == "DCCLXXXIX")
assert(romanNumeral(2421) == "MMCDXXI")
assert(parseRomanNumeral("I") == Some(1))
assert(parseRomanNumeral("w") == None)
assert(parseRomanNumeral("VIII") == Some(8))
assert(parseRomanNumeral("XXXIX") == Some(39))
assert(parseRomanNumeral("CCXLVI") == Some(246))
assert(parseRomanNumeral("DCCLXXXIX") == Some(789))
assert(parseRomanNumeral("MMCDXXI") == Some(2421))
assert(
{
val randomNumber = scala.util.Random.nextInt(5000) + 1
parseRomanNumeral(romanNumeral(randomNumber)).contains(randomNumber)
},
"A random number is checked without issue"
)


## Algorithm in Scala

56 lines of Scala (compatible versions 2.13 & 3.0).