Life Goes On

まあまあだけど楽しんでる方です

42問目

http://projecteuler.net/index.php?section=problems&id=42
英単語に対して、「SKY : 19 + 11 + 25 = 55」のように得点を計算する。約2000個の単語を含むファイルの中に、得点が三角数となる単語がいくつあるか求める。
これも問題をそのまま書き下すだけ。
と思ったのですが、最初のテキスト処理のところで、もっと簡単なやり方がありました。もとのテキストの前後に"["、"]"を付けてリストとして読ませるのです。
ゆーふぇみずむ
コード量がぐっと減ります。上手いなぁ。

import Data.Char

main = do
    words' <- readFile "words.txt"
    print $ euler042 $ read $ "[" ++ words' ++ "]"
--    print $ euler042 $ words $ map replace words'

-- replace :: Char -> Char
-- replace '\"' = ' '
-- replace ',' = ' '
-- replace c = c

euler042 :: [String] -> Int
euler042 words = length $ filter (isTriangle . score) words

isTriangle :: Int -> Bool
isTriangle n = n == (head $ dropWhile (< n) triangles)

triangles :: [Int]
triangles = map (\ n -> div (n * (n + 1)) 2) [1..]

score :: String -> Int
score word = sum $ map (\ c -> ord c - ord 'A' + 1) word