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