Problem 89

http://projecteuler.net/index.php?section=problems&id=89

はじめは、入力として、

IIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIII

みたいなものもあるのかと思っていた。

import Data.List
import Data.Maybe
roman  [] xs = xs
roman  ((r,s):rs) xs
| isInfixOf r xs = roman changes.replace (r,s) $ xs
| otherwise = roman rs xs
replace _ [] = []
replace (r,s) (x:xs)
| isPrefixOf r (x:xs) = (s++).fromJust.stripPrefix r $ x:xs
| otherwise = x : replace (r,s) xs
changes =
[("DD","M"),("CCCCC","D"),("LL","C"),("XXXXX","L"),("VV","X"),("IIIII","V"),
("DCCCC","CM"),("CCCC","CD"),("LXXXX","XC"),("XXXX","XL"),("VIIII","IX"),("IIII","IV")]
main = readFile"roman.txt">>=print.sum.map diff.lines
where diff x = length x - (length.roman changes) x

後で分かったが、実は同じ文字は5つ以上連続しない、と問題文に明記してあった。

More Reading
Newer// Problem 94
Older// Problem 95