Created
February 24, 2012 01:33
-
-
Save asmuth/1896564 to your computer and use it in GitHub Desktop.
Roman Numerals to Integer (learning scala) :)
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
import scala.collection.immutable.HashMap; | |
val tbl = HashMap[Char, Int]( | |
'M' -> 1000, | |
'D' -> 500, | |
'C' -> 100, | |
'L' -> 50, | |
'X' -> 10, | |
'V' -> 5, | |
'I' -> 1 | |
) | |
def romanToArabic(roman: String) : Int = { | |
(0 /: ((roman.toCharArray :\ List(List[Char]())) ((c: Char, m: List[List[Char]]) => { | |
if ((m.head.size > 0) && (tbl(c) < tbl(m.head.head))) | |
List((List(c) ++ m.head)) ++ m.tail | |
else | |
List(List(c), m.head) ++ m.tail | |
})))((m: Int, l: List[Char]) => { | |
if (l.size == 1) | |
m + tbl(l.head) | |
else if (l.size == 0) | |
m | |
else | |
m + (tbl(l.reverse.head) /: l.reverse.tail)(_ - tbl(_)) | |
}) | |
} | |
val test1 = romanToArabic("MCMLXXXV") | |
println((test1, test1 == 1985)) | |
val test2 = romanToArabic("MCMXC") | |
println((test2, test2 == 1990)) | |
val test3 = romanToArabic("MDCCCCX") | |
println((test3, test3 == 1910)) | |
val test4 = romanToArabic("MCMXCII") | |
println((test4, test4 == 1992)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment