-
Notifications
You must be signed in to change notification settings - Fork 0
/
problem_042.hs
39 lines (30 loc) · 1.07 KB
/
problem_042.hs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
import Data.List
problem42 :: IO Int
problem42 = do
content <- readFile "files/problem_042.txt"
return $ length
$ filter isTriangleWord
$ map calculateValue
$ readWords content
isTriangleWord :: Int -> Bool
isTriangleWord value = elem value $ takeWhile (<= value) triangleNumbers
calculateValue :: [Char] -> Int
calculateValue = sum . map (\x -> position x alphabet)
position :: Eq a => a -> [a] -> Int
position char alphabet =
case elemIndex char alphabet of
Just index -> index + 1
Nothing -> 0
triangleNumbers :: [Int]
triangleNumbers = [n * (n + 1) `quot` 2 | n <- [1..]]
alphabet :: [Char]
alphabet = ['A'..'Z']
readWords :: [Char] -> [String]
readWords str = map (\x -> strip "\"" x) $ split ',' str
-- http://stackoverflow.com/questions/4978578/how-to-split-a-string-in-haskell
split :: Eq a => a -> [a] -> [[a]]
split d [] = []
split d s = x : split d (drop 1 y) where (x,y) = span (/= d) s
-- http://www.rosettacode.org/wiki/Strip_a_set_of_characters_from_a_string#Haskell
strip :: String -> String -> String
strip = filter . flip notElem