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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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.