···11+{-# LANGUAGE LambdaCase #-}
22+33+import qualified Data.Set as S
44+import System.Environment (getArgs)
55+66+parse :: String -> Int
77+parse ('+' : f) = read f
88+parse f = read f
99+1010+p1 = sum
1111+1212+p2 n = firstDup $ scanl1 (+) (cycle n)
1313+1414+firstDup = go S.empty
1515+ where
1616+ go seen (x : xs) = if S.member x seen then x else go (S.insert x seen) xs
1717+1818+main = do
1919+ n <-
2020+ fmap (map parse . lines) $
2121+ getArgs
2222+ >>= \case
2323+ ["-"] -> getContents
2424+ [file] -> readFile file
2525+ print $ p1 n
2626+ print $ p2 n
+25
src/2018/02.lhs
···11+{-# LANGUAGE LambdaCase #-}
22+33+import qualified Data.Map as M
44+import System.Environment (getArgs)
55+66+freqs = M.fromListWith (+) . map (,1)
77+88+p1 n = occurs 2 fqs * occurs 3 fqs
99+ where
1010+ fqs = map freqs n
1111+ occurs n = length . filter (not . M.null . M.filter (== n))
1212+1313+lev x y = sum [1 | (a, b) <- zip x y, a /= b]
1414+1515+p2 n = [(a, b) | a <- n, b <- n, a /= b, lev a b == 1]
1616+1717+main = do
1818+ n <-
1919+ fmap lines $
2020+ getArgs
2121+ >>= \case
2222+ ["-"] -> getContents
2323+ [file] -> readFile file
2424+ print $ p1 n
2525+ print $ p2 n
+49
src/2018/03.lhs
···11+{-# LANGUAGE LambdaCase #-}
22+33+import Data.List.Split (splitOn)
44+import qualified Data.Map as M
55+import qualified Data.Set as S
66+import System.Environment (getArgs)
77+88+parse :: String -> (Int, (Int, Int), (Int, Int))
99+parse l = (read (tail a), (read x, read y), (read w, read h))
1010+ where
1111+ [a, b, c, d] = splitOn " " l
1212+ [x, y] = splitOn "," (init c)
1313+ [w, h] = splitOn "x" d
1414+1515+grid =
1616+ M.fromList
1717+ [ ((x, y), [])
1818+ | x <- [0 .. 999],
1919+ y <- [0 .. 999]
2020+ ]
2121+2222+claim grid (id, (x, y), (w, h)) = foldl conv grid subgrid
2323+ where
2424+ subgrid = [(x', y') | x' <- [x .. x + w - 1], y' <- [y .. y + h - 1]]
2525+ conv g (x', y') = M.adjust (id :) (x', y') g
2626+2727+p1 n = M.size $ M.filter ((> 1) . length) $ foldl claim grid n
2828+2929+(-|-) x y = (x S.\\ y) `S.union` (y S.\\ x)
3030+3131+p2 n = a -|- seen
3232+ where
3333+ a = S.fromList $ map (\(a, _, _) -> a) n
3434+ seen =
3535+ foldl1 S.union $
3636+ map S.fromList $
3737+ M.elems $
3838+ M.filter ((> 1) . length) $
3939+ foldl claim grid n
4040+4141+main = do
4242+ n <-
4343+ fmap (map parse . lines) $
4444+ getArgs
4545+ >>= \case
4646+ ["-"] -> getContents
4747+ [file] -> readFile file
4848+ print $ p1 n
4949+ print $ p2 n