import scala.collection.SortedMap
def roman(x:Int): String = {
val romanLiteral = SortedMap(1000 -> "M", 900 -> "CM", 500 -> "D", 400 -> "CD",
100 -> "C", 90 -> "XC", 50 -> "L", 40 -> "XL", 10 -> "X", 9 -> "IX", 5 ->
"V", 4 -> "IV", 1 -> "I")
val arab = romanLiteral.keySet.toList.reverse
def r(n:Int,idx:Int,romanNumber:StringBuilder): String = {
val a = arab(idx)
if (n==0)
romanNumber.toString
else if ( n >= a )
r( n-a, idx, romanNumber append romanLiteral(a) )
else
r( n, idx+1, romanNumber )
}
r(x,0,new StringBuilder())
}
(1 to 100).foreach( x => printf( "%s=%s\n", x, roman(x) ))
Mittwoch, 17. Februar 2010
Arabic-Roman numerals converter written in Scala
A simple arabic to roman numeral converter written in Scala
Abonnieren
Kommentare zum Post (Atom)
Keine Kommentare:
Kommentar veröffentlichen