//
you're reading...
Dojo, Scala

Roman Numerals in Scala

We were supplied with the following Kata/Problem Description : Create a method which outputs the Roman Numeral equivalent for a supplied, positive integer.  The output should output the shortest possible format and should apply the following conventions

For further details of Roman Numerals see http://projecteuler.net/about=roman_numerals

Solution

This problem looked like a perfect example to practice a bit of my recently learnt Scala.  I used a technique to recursively invoke a method with a list of tuples containing the definition of the roman numerals and divide the ‘head’ element into the number and then pass the mod of the division with the tail of the list to the next recursion.

The Scala implementation shown below provided a very compact and yet thoroughly readable implementation of the required algorithm.


class RomanNumeral {
def toRomanNumerals( number: Int) : String = {
toRomanNumerals( number, List( ("M", 1000),("CM", 900), ("D", 500), ("CD", 400), ("C", 100), ("XC", 90),
("L", 50), ("XL",40), ("X", 10), ("IX", 9), ("V", 5), ("IV", 4), ("I", 1) ))
}
private def toRomanNumerals( number: Int, digits: List[(String, Int)] ) : String = digits match {
case Nil => ""
case h :: t => h._1 * ( number / h._2 ) + toRomanNumerals( number % h._2, t )
}
}

Discussion

No comments yet.

Leave a comment

Archives

Categories

July 2012
M T W T F S S
 1
2345678
9101112131415
16171819202122
23242526272829
3031