Day 2
[advent-of-code-18.git] / src / advent02 / advent02.hs
1 import Data.List
2
3
4 main :: IO ()
5 main = do
6 text <- readFile "data/advent02.txt"
7 let ids = lines text
8 print $ part1 ids
9 putStrLn $ part2 ids
10
11 part1 ids = (fst counts23) * (snd counts23)
12 where allLetterCounts = map letterCounts ids
13 counts23 = foldl' addCounts (0, 0) allLetterCounts
14
15 letterCounts :: String -> [Int]
16 letterCounts = map length . group . sort
17
18 addCounts :: (Int, Int) -> [Int] -> (Int, Int)
19 addCounts (twos, threes) counts = (twos', threes')
20 where twos' = if has2 counts then twos + 1 else twos
21 threes' = if has3 counts then threes + 1 else threes
22
23 has2 = elem 2
24 has3 = elem 3
25
26 part2 ids = uncurry sameChars closeIds
27 where closeIds = head $ filter (\ab -> uncurry differenceCount ab == 1) [(a, b) | a <- ids, b <- ids]
28
29 differenceCount :: String -> String -> Int
30 differenceCount this that = length $ filter (\(a, b) -> a /= b) $ zip this that
31
32 sameChars :: String -> String -> String
33 sameChars this that = map fst $ filter (\(a, b) -> a == b) $ zip this that
34