ローマ数字の変換
30分プログラム、その797。anarchy golf - Roman numeralにインスパイアされました。
ローマ数字をIntに変換します。面倒だったので、I,V,Xにしか対応していません。
使い方
scala> Roman.toInt("II")
res39: Int = 2
scala> Roman.toInt("IIV")
res40: Int = 3
scala> Roman.toInt("XIV")
res38: Int = 14
ソースコード
object Roman { val map = Map('I' -> 1, 'V' -> 5, 'X' -> 10) def toInt(s : String) : Int = s.foldRight((0,0)){ case (c, (m, current)) => val n = map(c) if(n < m){ (m, current - n) }else{ (n max m, current + n) } }._2 }