├── .gitignore ├── 10a.hs ├── 10b.hs ├── 11a.hs ├── 11b.hs ├── 12a.hs ├── 12b.hs ├── 13a.hs ├── 13b.hs ├── 14a.hs ├── 14b.hs ├── 15a.hs ├── 15b.hs ├── 16a.hs ├── 16b.hs ├── 17a.hs ├── 17b.hs ├── 17c.hs ├── 18a.hs ├── 18b.hs ├── 19a.hs ├── 19b.hs ├── 1a.hs ├── 1b.hs ├── 20a.hs ├── 20b.hs ├── 21a.hs ├── 21b.hs ├── 22a.hs ├── 22b.hs ├── 23a.hs ├── 23b.hs ├── 24a.hs ├── 24b.hs ├── 25a.hs ├── 2a.hs ├── 2b.hs ├── 3a.hs ├── 3b.hs ├── 4a.hs ├── 4b.hs ├── 5a.hs ├── 5b.hs ├── 6a.hs ├── 6b.hs ├── 7a.hs ├── 7b.hs ├── 8a.hs ├── 8b.hs ├── 9a.hs ├── 9b.hs ├── AOC.hs ├── LICENSE ├── Makefile ├── README.md ├── get └── watcher /.gitignore: -------------------------------------------------------------------------------- 1 | dist 2 | dist-* 3 | cabal-dev 4 | *.o 5 | *.hi 6 | *.hie 7 | *.chi 8 | *.chs.h 9 | *.dyn_o 10 | *.dyn_hi 11 | .hpc 12 | .hsenv 13 | .cabal-sandbox/ 14 | cabal.sandbox.config 15 | *.prof 16 | *.aux 17 | *.hp 18 | *.eventlog 19 | .stack-work/ 20 | cabal.project.local 21 | cabal.project.local~ 22 | .HTF/ 23 | .ghc.environment.* 24 | .cookie 25 | [1-9][abc] 26 | [12][0-9][abc] 27 | *.input 28 | *.output 29 | doc/ 30 | AOC.txt 31 | .expected_output 32 | -------------------------------------------------------------------------------- /10a.hs: -------------------------------------------------------------------------------- 1 | import AOC 2 | 3 | main = interact $ f . map read 4 | 5 | f :: [Int] -> Int 6 | f xs = get1diffs * get3diffs 7 | where 8 | all = 0:sort xs ++ [deviceRating] 9 | deviceRating = maximum xs + 3 10 | getdiffs = zipWith (-) (tail all) all 11 | get1diffs = count 1 getdiffs 12 | get3diffs = count 3 getdiffs 13 | -------------------------------------------------------------------------------- /10b.hs: -------------------------------------------------------------------------------- 1 | import AOC 2 | 3 | main = interact $ f . map read 4 | 5 | f :: [Int] -> Int 6 | f xs = summarize (all, getChildren) calc 0 7 | where 8 | all = 0:sort xs ++ [maximum xs + 3] 9 | getChildren j = [(1, k) | k <- [j + 1 .. j + 3], k `elem` all] 10 | calc [] = 1 11 | calc xs = sum $ map snd xs 12 | -------------------------------------------------------------------------------- /11a.hs: -------------------------------------------------------------------------------- 1 | import AOC 2 | 3 | main = interact f 4 | 5 | f = count '#' . concat . mapnbsC nbs8 g 6 | where 7 | g x ns = case x of 8 | 'L' -> if count '#' ns == 0 then '#' else 'L' 9 | '#' -> if count '#' ns >= 4 then 'L' else '#' 10 | x -> x 11 | -------------------------------------------------------------------------------- /11b.hs: -------------------------------------------------------------------------------- 1 | import AOC 2 | 3 | main = interact f 4 | 5 | f = count '#' . concat . maplosC nbs8 (=='.') g 6 | where 7 | g x ns = case x of 8 | 'L' -> if count '#' ns == 0 then '#' else 'L' 9 | '#' -> if count '#' ns >= 5 then 'L' else '#' 10 | x -> x 11 | -------------------------------------------------------------------------------- /12a.hs: -------------------------------------------------------------------------------- 1 | import AOC 2 | 3 | main = interact f 4 | 5 | m :: ((Int, Int), (Int, Int)) -> String -> ((Int, Int), (Int, Int)) 6 | m s (x:xs) = m' s x $ read xs 7 | where 8 | m' (x, v) 'F' n = (x + (n *$ v), v) 9 | m' (x, v) 'L' n = (x, rotn (n `div` 90) v) 10 | m' (x, v) 'R' n = m' (x, v) 'L' (-n) 11 | m' (x, v) v' n = (x + (n *$ dir v'), v) 12 | 13 | f :: [String] -> Int 14 | f xs = manhattan $ fst $ foldl' m (0, dir 'E') xs 15 | -------------------------------------------------------------------------------- /12b.hs: -------------------------------------------------------------------------------- 1 | import AOC 2 | 3 | main = interact f 4 | 5 | m :: ((Int, Int), (Int, Int)) -> String -> ((Int, Int), (Int, Int)) 6 | m s (x:xs) = m' s x $ read xs 7 | where 8 | m' (x, v) 'F' n = (x + (n *$ v), v) 9 | m' (x, v) 'L' n = (x, rotn (n `div` 90) v) 10 | m' (x, v) 'R' n = m' (x, v) 'L' (-n) 11 | m' (x, v) v' n = (x, v + (n *$ dir v')) 12 | 13 | f :: [String] -> Int 14 | f xs = manhattan $ fst $ foldl' m (0, (10, 1)) xs 15 | -------------------------------------------------------------------------------- /13a.hs: -------------------------------------------------------------------------------- 1 | import AOC 2 | 3 | main = interact f 4 | 5 | f [ts, bs] = getResult $ minimum $ map busTime bs' 6 | where 7 | ts' = read ts 8 | bs' = mapMaybe readBus $ splitOn "," bs 9 | readBus "x" = Nothing 10 | readBus s = Just $ read s 11 | busTime x = (x - ts' `mod` x, x) 12 | getResult (t, b) = t * b 13 | -------------------------------------------------------------------------------- /13b.hs: -------------------------------------------------------------------------------- 1 | import AOC 2 | 3 | main = interact f 4 | 5 | -- Solution inspired by Uncle Bob: https://youtu.be/tHTDAUV-VsM?t=489 6 | next :: Integer -> Integer -> [(Integer, Integer)] -> Integer 7 | next i m [] = i 8 | next i m bs@((n, x):bs') = if (i + n) `rem` x == 0 then next i (m*x) bs' else next (i + m) m bs 9 | 10 | f [_, bs] = next 0 1 bs' 11 | where 12 | bs' = fst $ foldl' g ([], 0) $ map readBus $ splitOn "," bs 13 | g (xs, j) Nothing = (xs, j + 1) 14 | g (xs, j) (Just n) = (xs ++ [(j, n)], j + 1) 15 | readBus "x" = Nothing 16 | readBus s = Just $ read s 17 | -------------------------------------------------------------------------------- /14a.hs: -------------------------------------------------------------------------------- 1 | import AOC 2 | import qualified Data.IntMap as M 3 | import Data.Bits 4 | 5 | main = interact $ f . parselist (try loadp <|> maskp) 6 | 7 | data Instr = Mask (Int, Int) | Load Int Int deriving (Show, Eq, Read, Ord) 8 | 9 | loadp :: Parser Instr 10 | loadp = do 11 | string "mem[" 12 | addr <- integer 13 | string "] = " 14 | val <- integer 15 | return $ Load addr val 16 | 17 | maskp :: Parser Instr 18 | maskp = do 19 | string "mask = " 20 | mask <- many1 anyChar 21 | return $ Mask $ readMask mask 22 | 23 | readMask :: String -> (Int, Int) 24 | readMask = foldl' (\x y -> 2 *$ x + readMask' y) 0 25 | where 26 | readMask' 'X' = (1, 0) 27 | readMask' '0' = (0, 0) 28 | readMask' '1' = (0, 1) 29 | 30 | f is = sum $ snd $ foldl' exec (0, M.empty) is 31 | where 32 | exec (mask, mem) (Load addr val) = (mask, M.insert addr (applyMask mask val) mem) 33 | exec (mask, mem) (Mask x) = (x, mem) 34 | applyMask (mask, set) val = set .|. val .&. mask 35 | -------------------------------------------------------------------------------- /14b.hs: -------------------------------------------------------------------------------- 1 | import AOC 2 | import qualified Data.IntMap as M 3 | import Data.Bits 4 | 5 | main = interact $ f . parselist (try loadp <|> maskp) 6 | 7 | data Instr = Mask (Int, Int) | Load Int Int deriving (Show, Eq, Read, Ord) 8 | 9 | loadp :: Parser Instr 10 | loadp = do 11 | string "mem[" 12 | addr <- integer 13 | string "] = " 14 | val <- integer 15 | return $ Load addr val 16 | 17 | maskp :: Parser Instr 18 | maskp = do 19 | string "mask = " 20 | mask <- many1 anyChar 21 | return $ Mask $ readMask mask 22 | 23 | readMask :: String -> (Int, Int) 24 | readMask = foldl' (\x y -> 2 *$ x + readMask' y) 0 25 | where 26 | readMask' 'X' = (1, 0) 27 | readMask' '0' = (0, 0) 28 | readMask' '1' = (0, 1) 29 | 30 | f is = sum $ snd $ foldl' exec (0, M.empty) is 31 | where 32 | exec (mask, mem) (Load addr val) = (mask, updateMap addr mask val mem) 33 | exec (mask, mem) (Mask x) = (x, mem) 34 | updateMap addr mask val mem = insertMany val (flAddrs mask addr) mem 35 | insertMany val addrs m = foldl' (\m' a -> M.insert a val m') m addrs 36 | flAddrs (mask, set) addr = map (\x -> sum x .|. set .|. addr .&. complement mask) $ floatingAddresses mask 37 | floatingAddresses mask = subsequences [bit b | b <- [0..35], testBit mask b] 38 | -------------------------------------------------------------------------------- /15a.hs: -------------------------------------------------------------------------------- 1 | import AOC 2 | 3 | main = interact' $ f . map read . splitOn "," 4 | 5 | nn = 2020 6 | 7 | f :: [Int] -> Int 8 | f xs = head $ getList nn 9 | where 10 | getList n | n <= length xs = reverse $ take n xs 11 | getList n = let (y:ys) = getList (n - 1) 12 | y' = if y `elem` ys 13 | then 1 + length (takeWhile (/= y) ys) 14 | else 0 15 | in y':y:ys 16 | -------------------------------------------------------------------------------- /15b.hs: -------------------------------------------------------------------------------- 1 | import AOC 2 | import Control.Monad.ST 3 | import qualified Data.Vector.Unboxed.Mutable as V 4 | import qualified Data.IntMap as M 5 | 6 | main = interact' $ f . map read . splitOn "," 7 | 8 | nn = 30000000 9 | 10 | f :: [Int] -> Int 11 | f xs = if nn < l then xs !! (nn - 1) else get' 12 | where 13 | l = length xs 14 | get' = runST $ do 15 | let y = last xs 16 | v <- V.new nn 17 | zipWithM_ (V.write v) (init xs) [1..] 18 | stepM y l v 19 | stepM :: Int -> Int -> V.MVector s Int -> ST s Int 20 | stepM !y !i _ | i == nn = return y 21 | stepM !y !i v = do 22 | n <- V.read v y 23 | V.write v y i 24 | stepM (if n == 0 then 0 else i - n) (i + 1) v 25 | 26 | f' :: [Int] -> Int 27 | f' xs = get nn 28 | where 29 | l = length xs 30 | get i = if i < l then xs !! (i - 1) else get' i 31 | get' target = step (target - l) (last xs) (l - 1) (M.fromList $ zip (init xs) [0..]) 32 | step 0 y _ _ = y 33 | step target' y i m = 34 | let y' = case m M.!? y of 35 | Just n -> i - n 36 | Nothing -> 0 37 | in step (target' - 1) y' (i + 1) (M.insert y i m) 38 | -------------------------------------------------------------------------------- /16a.hs: -------------------------------------------------------------------------------- 1 | import AOC 2 | 3 | main = interactg f 4 | 5 | attribp :: String -> Int -> Bool 6 | attribp s = or . mapM inRange rules 7 | where 8 | [_, rs] = splitOn ": " s 9 | rules = map (map read . splitOn "-") $ splitOn " or " rs 10 | inRange [low, high] x = low <= x && x <= high 11 | 12 | attribp' :: String -> [Int] 13 | attribp' s = concatMap valid rules 14 | where 15 | [_, rs] = splitOn ": " s 16 | rules = map (map read . splitOn "-") $ splitOn " or " rs 17 | valid [low, high] = [low..high] 18 | 19 | ticketp :: String -> [Int] 20 | ticketp = map read . splitOn "," 21 | 22 | f [as, [_, t], _:ts] = sum $ filter matchesNoRules $ concat tickets 23 | where 24 | (attribs, tickets) = (map attribp as, map ticketp ts) 25 | matchesNoRules = not . or . sequence attribs 26 | 27 | f' [as, [_, t], _:ts] = sum $ filter (`notElem` validNums) $ concat tickets 28 | where 29 | (attribs, _, tickets) = (map attribp' as, ticketp t, map ticketp ts) 30 | validNums = nub $ concat attribs 31 | -------------------------------------------------------------------------------- /16b.hs: -------------------------------------------------------------------------------- 1 | import AOC 2 | 3 | main = interactg f 4 | 5 | attribp :: String -> (String, Int -> Bool) 6 | attribp s = (name, or . mapM inRange rules) 7 | where 8 | [name, rs] = splitOn ": " s 9 | rules = map (map read . splitOn "-") $ splitOn " or " rs 10 | inRange [low, high] x = low <= x && x <= high 11 | 12 | ticketp :: String -> [Int] 13 | ticketp = map read . splitOn "," 14 | 15 | f [as, [_, t], _:ts] = product $ map fst $ filter (isPrefixOf "departure" . snd) $ zip ticket fieldNames 16 | where 17 | (attribs, ticket, tickets) = (map attribp as, ticketp t, map ticketp ts) 18 | matchesAnyRule = or . mapM snd attribs 19 | tickets' = filter (all matchesAnyRule) tickets 20 | 21 | attributes = map filterAttribs $ transpose tickets' 22 | filterAttribs xs = map fst $ filter (\(_, r) -> all r xs) attribs 23 | 24 | fieldNames = map head $ converge removeKnowns attributes 25 | removeKnowns names = let knowns = concat $ filter ((==1) . length) names 26 | doRemove ns = if length ns /= 1 27 | then filter (`notElem` knowns) ns 28 | else ns 29 | in map doRemove names 30 | -------------------------------------------------------------------------------- /17a.hs: -------------------------------------------------------------------------------- 1 | import AOC 2 | 3 | main = interact $ f . map (map (=='#')) 4 | 5 | n = 6 6 | 7 | f m = count True $ elems $ mapnbs3N n nbs26 conwayRule False [m] 8 | -------------------------------------------------------------------------------- /17b.hs: -------------------------------------------------------------------------------- 1 | import AOC 2 | 3 | main = interact $ f . map (map (=='#')) 4 | 5 | n = 6 6 | 7 | f m = count True $ elems $ mapnbs4N n nbs80 conwayRule False [[m]] 8 | -------------------------------------------------------------------------------- /17c.hs: -------------------------------------------------------------------------------- 1 | import AOC 2 | import qualified Data.Vector as V 3 | import qualified Data.Map as M 4 | 5 | instance Num a => Num (Vector a) where 6 | x + y = V.zipWith (+) x y 7 | x * y = V.zipWith (*) x y 8 | abs = V.map abs 9 | signum = V.map signum 10 | fromInteger = V.singleton . fromInteger 11 | negate = V.map negate 12 | 13 | main = interact $ f . map (map (=='#')) 14 | 15 | dd = 4 16 | nn = 6 17 | 18 | mapnbs' :: [Vector Int] -> (Bool -> [Bool] -> Bool) -> M.Map (Vector Int) Bool -> M.Map (Vector Int) Bool 19 | mapnbs' nbs f m = M.fromList $ filter snd $ map nextval ks' 20 | where 21 | nextval k = (k, f (get k) (map (get . (k+)) nbs)) 22 | get k = fromMaybe False (m M.!? k) 23 | ks = M.keys m 24 | a = V.map (+ (-1)) $ foldl1' (V.zipWith min) ks -- top-left-front-... corner of bounding box 25 | z = V.map (+1) $ foldl1' (V.zipWith max) ks -- bottom-right-back-... corner 26 | ks' = map V.fromList $ foldr (\x y -> (:) <$> x <*> y) [[]] $ V.zipWith (\x y -> [x..y]) a z 27 | 28 | nbs n = delete (V.replicate n 0) (nbs' n) 29 | where 30 | nbs' 0 = [V.empty] 31 | nbs' n = let v = nbs' (n-1) in V.cons <$> [-1..1] <*> v 32 | 33 | ltomap :: [[Bool]] -> M.Map (Vector Int) Bool 34 | ltomap xss = M.fromList $ filter snd $ concatMap (\(j, row) -> zipWith (\i x -> (V.fromList (i:j:replicate (dd - 2) 0),x)) [0..] row) $ zip [0..] xss 35 | 36 | f ts = countActive $ applyN nn domap $ ltomap ts 37 | where 38 | domap = mapnbs' (nbs dd) conwayRule 39 | countActive = count True . M.elems 40 | -------------------------------------------------------------------------------- /18a.hs: -------------------------------------------------------------------------------- 1 | import AOC 2 | 3 | expr = buildExpressionParser table term 4 | term = paren <|> integer 5 | paren = char '(' *> expr <* char ')' 6 | table = [[Infix (char '+' >> return (+)) AssocLeft, Infix (char '*' >> return (*)) AssocLeft]] 7 | 8 | main = interact' $ sum . parselist expr . lines . filter (/=' ') 9 | -------------------------------------------------------------------------------- /18b.hs: -------------------------------------------------------------------------------- 1 | import AOC 2 | 3 | expr = buildExpressionParser table term 4 | term = paren <|> integer 5 | paren = char '(' *> expr <* char ')' 6 | table = [[Infix (char '+' >> return (+)) AssocLeft], [Infix (char '*' >> return (*)) AssocLeft]] 7 | 8 | main = interact' $ sum . parselist expr . lines . filter (/=' ') 9 | -------------------------------------------------------------------------------- /19a.hs: -------------------------------------------------------------------------------- 1 | import AOC 2 | import qualified Data.Map as M 3 | 4 | main = interactg f 5 | 6 | data Rule = Letter Char | And Rule Rule | Or Rule Rule | See Int deriving (Show, Eq, Read, Ord) 7 | 8 | rulep :: String -> (Int, Rule) 9 | rulep xs = (read $ init n, rs) 10 | where 11 | Right rs = parse rulep' $ unwords xs' 12 | (n:xs') = words xs 13 | rulep' = buildExpressionParser table term 14 | term = ((See <$> integer) <|> char '"' *> (Letter <$> anyChar) <* char '"') <* spaces 15 | table = [[Infix (spaces >> return And) AssocLeft], [Infix (char '|' >> spaces >> return Or) AssocLeft]] 16 | 17 | mkParser :: M.Map Int Rule -> Rule -> Parser () 18 | mkParser _ (Letter c) = void $ char c 19 | mkParser m (And x y) = mkParser m x >> mkParser m y 20 | mkParser m (Or x y) = try (mkParser m x) <|> mkParser m y 21 | mkParser m (See x) = mkParser m (m M.! x) 22 | 23 | f [rs, ss] = count True $ map check ss 24 | where 25 | m = M.fromList $ map rulep rs 26 | p = mkParser m (See 0) 27 | check s = isRight $ parse (p >> eof) s 28 | -------------------------------------------------------------------------------- /19b.hs: -------------------------------------------------------------------------------- 1 | import AOC 2 | import qualified Data.Map as M 3 | 4 | main = interactg f 5 | 6 | data Rule = Letter Char | And Rule Rule | Or Rule Rule | See Int deriving (Show, Eq, Read, Ord) 7 | 8 | rulep :: String -> (Int, Rule) 9 | rulep xs = (read $ init n, rs) 10 | where 11 | Right rs = parse rulep' $ unwords xs' 12 | (n:xs') = words xs 13 | rulep' = buildExpressionParser table term 14 | term = ((See <$> integer) <|> char '"' *> (Letter <$> anyChar) <* char '"') <* spaces 15 | table = [[Infix (spaces >> return And) AssocLeft], [Infix (char '|' >> spaces >> return Or) AssocLeft]] 16 | 17 | mkParser :: M.Map Int Rule -> Rule -> Parser () 18 | mkParser _ (Letter c) = void $ char c 19 | mkParser m (And x y) = mkParser m x >> mkParser m y 20 | mkParser m (Or x y) = try (mkParser m x) <|> mkParser m y 21 | mkParser m (See x) = mkParser m (m M.! x) 22 | 23 | f [rs, ss] = count True $ map check ss 24 | where 25 | m = M.fromList $ map rulep rs 26 | p = do 27 | r42 <- many1 $ try $ mkParser m $ See 42 28 | r31 <- many1 $ mkParser m $ See 31 29 | guard $ length r42 > length r31 30 | check s = isRight $ parse (p >> eof) s 31 | -------------------------------------------------------------------------------- /1a.hs: -------------------------------------------------------------------------------- 1 | import AOC 2 | 3 | main = interact $ f . map read 4 | 5 | f (x:xs) = if (2020 - x) `elem` xs then x * (2020 - x) else f xs 6 | -------------------------------------------------------------------------------- /1b.hs: -------------------------------------------------------------------------------- 1 | import AOC 2 | 3 | main = interact $ f' . map read 4 | 5 | f' (x:xs) = case f (2020 - x) xs of 6 | Nothing -> f' xs 7 | Just y -> y * x 8 | 9 | f n (x:xs) = if (n - x) `elem` xs then Just (x * (n - x)) else f n xs 10 | f _ [] = Nothing 11 | -------------------------------------------------------------------------------- /20a.hs: -------------------------------------------------------------------------------- 1 | import AOC 2 | import Data.List.Extra 3 | 4 | main = interactg f 5 | 6 | data Orientation = Ori Bool Int deriving (Show, Eq, Read, Ord) 7 | 8 | rotgrid = transpose . reverse 9 | rotgridn n = applyN n rotgrid 10 | 11 | orients = [Ori flipped nrots | flipped <- [False, True], nrots <- [0..3]] 12 | orient (Ori False n) = rotgridn n 13 | orient (Ori True n) = rotgridn n . reverse 14 | 15 | getorients g = [orient o g | o <- orients] 16 | 17 | boolsToInt :: [Bool] -> Int 18 | boolsToInt = fromJust . readBin 19 | 20 | g :: [String] -> (Int, [[Bool]]) 21 | g (t:s) = (read $ init t', s') 22 | where 23 | (_:t':_) = words t 24 | s' = map (map (=='#')) s 25 | 26 | f s = product cornerTiles 27 | where 28 | tiles = map g $ filter (not . null) s 29 | testtile = head tiles 30 | getInts (tnum, tile) = map ((,tnum) . boolsToInt . head) $ getorients tile 31 | tileIntMapping = concatMap getInts tiles 32 | uniqueEdges = filter ((==1) . length) $ groupOn fst $ sort tileIntMapping 33 | -- corner tiles are tiles with 4 unique edges (2 edges * 2 orientations) 34 | cornerTiles = map head $ filter ((==4) . length) $ group $ sort $ map (snd . head) uniqueEdges 35 | -------------------------------------------------------------------------------- /20b.hs: -------------------------------------------------------------------------------- 1 | import AOC 2 | import Data.Bits 3 | import qualified Data.Map as M 4 | import Data.List.Extra 5 | import Data.Tuple.Extra 6 | 7 | main = interactg f 8 | 9 | data Orientation = Ori Bool Int deriving (Show, Eq, Read, Ord) 10 | 11 | rotgrid = transpose . reverse 12 | rotgridn n = applyN n rotgrid 13 | 14 | orients = [Ori flipped nrots | flipped <- [False, True], nrots <- [0..3]] 15 | orient (Ori False n) = rotgridn n 16 | orient (Ori True n) = rotgridn n . reverse 17 | 18 | getorients g = [(o, orient o g) | o <- orients] 19 | 20 | boolsToInt :: [Bool] -> Int 21 | boolsToInt = fromJust . readBin 22 | 23 | monster = map (map (=='#')) [" # ", "# ## ## ###", " # # # # # # "] 24 | monsterSig = mkSig monster 25 | 26 | mkSig :: [[Bool]] -> Int 27 | mkSig ss = boolsToInt $ concatMap (take 20) $ take 3 ss 28 | 29 | findMonsters :: [[Bool]] -> Int 30 | findMonsters ss = maximum $ map (uncurry findMonsters' . dupe . snd) $ getorients ss 31 | where 32 | findMonsters' ss0 ss = if length ss < 3 33 | then 0 34 | else 35 | (if mkSig ss .&. monsterSig == monsterSig then 1 else 0) + 36 | if length (head ss) > 20 then 37 | findMonsters' ss0 (map tail ss) 38 | else 39 | let ss0' = tail ss0 in findMonsters' ss0' ss0' 40 | 41 | g :: [String] -> (Int, [[Bool]]) 42 | g (t:s) = (read $ init t', s') 43 | where 44 | (_:t':_) = words t 45 | s' = map (map (=='#')) s 46 | 47 | showMap = unlines . map (map (bool '.' '#')) 48 | 49 | f s = count True (concat completeGrid) - findMonsters completeGrid * count True (concat monster) 50 | where 51 | tiles = map g $ filter (not . null) s 52 | getInts (tnum, tile) = map (\(o, tile') -> (boolsToInt $ head tile', (o, tnum, tile'))) $ getorients tile 53 | tileIntMapping = concatMap getInts tiles 54 | uniqueEdges = filter ((==1) . length) $ groupOn fst $ sort tileIntMapping 55 | -- corner tiles are tiles with 4 unique edges (2 edges * 2 orientations) 56 | cornerTiles = filter ((==4) . length) $ groupOn t2 $ sortOn t2 $ map (snd . head) uniqueEdges 57 | 58 | tileMap = M.fromListWith (++) $ map (\(edge, (_, tnum, tile)) -> (edge, [(tnum, tile)])) tileIntMapping 59 | 60 | stTiles = filter (\(Ori fl _, _, _) -> not fl) $ head cornerTiles 61 | stGrid = let [(o1, t1), (o2, t2)] = map (\(Ori _ n, _, t) -> (n, t)) stTiles 62 | in if o2 == succ o1 `mod` 4 then t1 else t2 63 | stTile = (t2 $ head stTiles, stGrid) 64 | 65 | belowTiles (n, t) = case filter ((/=n) . fst) $ tileMap M.! boolsToInt (last t) of 66 | [nexttile] -> (n, t):belowTiles nexttile 67 | _ -> [(n, t)] 68 | rightTiles (n, t) = map (transpose . snd) $ belowTiles (n, transpose t) 69 | 70 | mid = tail . init 71 | allTiles = map (map (mid . map mid) . rightTiles) $ belowTiles stTile 72 | allTilesRows = map (foldl1' (zipWith (++))) allTiles 73 | completeGrid = concat allTilesRows 74 | -------------------------------------------------------------------------------- /21a.hs: -------------------------------------------------------------------------------- 1 | import AOC 2 | import qualified Data.Map as M 3 | 4 | main = interact f 5 | 6 | f s = sum $ map (\a -> count a $ concatMap fst mapping) $ allIs \\ noAll 7 | where 8 | g [is, as] = (words is, splitOn ", " $ init as) 9 | mapping = map (g . splitOn " (contains ") s 10 | allIs = nub $ concatMap fst mapping 11 | allAs = nub $ concatMap snd mapping 12 | givenPossibilities = concatMap (\(is, as) -> map (,is) as) mapping 13 | asToIs = M.fromList $ map (,allIs) allAs 14 | allPossibilities = foldl' (\m (a, is) -> M.update (Just . intersect is) a m) asToIs givenPossibilities 15 | noAll = nub $ concat $ M.elems allPossibilities 16 | -------------------------------------------------------------------------------- /21b.hs: -------------------------------------------------------------------------------- 1 | import AOC 2 | import qualified Data.Map as M 3 | 4 | main = interact f 5 | 6 | f s = Str $ intercalate "," $ map (head . snd) remainingPossibilities 7 | where 8 | g [is, as] = (words is, splitOn ", " $ init as) 9 | mapping = map (g . splitOn " (contains ") s 10 | allIs = nub $ concatMap fst mapping 11 | allAs = nub $ concatMap snd mapping 12 | givenPossibilities = concatMap (\(is, as) -> map (,is) as) mapping 13 | asToIs = M.fromList $ map (,allIs) allAs 14 | allPossibilities = foldl' (\m (a, is) -> M.update (Just . intersect is) a m) asToIs givenPossibilities 15 | 16 | removeKnowns m = let knowns = concat $ filter ((==1) . length) $ map snd m 17 | in map (\(x, ys) -> (x, if length ys /= 1 then ys \\ knowns else ys)) m 18 | remainingPossibilities = sort $ converge removeKnowns $ M.toList allPossibilities 19 | -------------------------------------------------------------------------------- /22a.hs: -------------------------------------------------------------------------------- 1 | import AOC 2 | 3 | main = interactg f 4 | 5 | turn :: ([Int], [Int]) -> [Int] 6 | turn (c:cs, d:ds) = turn $ if c > d then (cs ++ [c, d], ds) else (cs, ds ++ [d, c]) 7 | turn ([], ds) = ds 8 | turn (cs, []) = cs 9 | 10 | f [_:p1, _:p2] = sum $ zipWith (*) [n,n-1..] cs' 11 | where 12 | cs = map read p1 13 | ds = map read p2 14 | cs' = turn (cs, ds) 15 | n = length cs' 16 | -------------------------------------------------------------------------------- /22b.hs: -------------------------------------------------------------------------------- 1 | import AOC 2 | import qualified Data.Set as S 3 | 4 | main = interactg f 5 | 6 | turn :: S.Set ([Int], [Int]) -> ([Int], Int, [Int], Int) -> (Bool, [Int]) 7 | turn !s (c:cs, cl, d:ds, dl) = if h `S.member` s 8 | then (True, c:cs) 9 | else turn s' $ if winner then (cs ++ [c, d], cl + 1, ds, dl - 1) else (cs, cl - 1, ds ++ [d, c], dl + 1) 10 | where 11 | h = (c:cs, d:ds) 12 | s' = S.insert h s 13 | winner = if cl > c && dl > d 14 | then fst $ turn S.empty (take c cs, c, take d ds, d) 15 | else c > d 16 | turn _ ([], _, ds, _) = (False, ds) 17 | turn _ (cs, _, [], _) = (True, cs) 18 | 19 | f [_:p1, _:p2] = sum $ zipWith (*) [n,n-1..] cs' 20 | where 21 | cs = map read p1 22 | ds = map read p2 23 | (_, cs') = turn S.empty (cs, length cs, ds, length ds) 24 | n = length cs' 25 | -------------------------------------------------------------------------------- /23a.hs: -------------------------------------------------------------------------------- 1 | import AOC 2 | import Data.Sequence 3 | import qualified Data.Sequence as S 4 | 5 | main = interact $ f . map digitToInt . head 6 | 7 | nIters = 100 8 | n = 9 9 | dec 0 = n - 1 10 | dec x = x - 1 11 | 12 | g (x:<|x2:<|x3:<|x4:<|xs) = g' x (dec x) (x2<|x3<|x4<|S.empty) xs 13 | where 14 | g' x0 x cs ds = if x `elem` cs then g' x0 (dec x) cs ds else g'' x0 x cs ds 15 | g'' x0 x cs ds = let (ds1, _:<|ds2) = spanl (/=x) ds in (ds1 >< x<|cs >< ds2) |> x0 16 | 17 | f xs = Str $ concatMap (show . (+1)) $ xs2 >< xs1 18 | where 19 | xs' = map (+ (-1)) xs 20 | (xs1, _:<|xs2) = spanl (/=0) $ applyN nIters g $ S.fromList xs' 21 | -------------------------------------------------------------------------------- /23b.hs: -------------------------------------------------------------------------------- 1 | import AOC 2 | import qualified Data.IntMap.Strict as IM 3 | import Data.IntMap ((!)) 4 | import Control.Monad.ST 5 | import qualified Data.Vector.Unboxed.Mutable as V 6 | 7 | main = interact $ f' . map digitToInt . head 8 | 9 | nIters = 10000000 10 | n = 1000000 11 | dec 0 = n - 1 12 | dec x = x - 1 13 | 14 | h :: V.MVector s Int -> Int -> ST s Int 15 | h v current = do 16 | x1 <- V.read v current 17 | x2 <- V.read v x1 18 | x3 <- V.read v x2 19 | next <- V.read v x3 20 | let dec' x = if x == x1 || x == x2 || x == x3 then dec' $ dec x else x 21 | x = dec' $ dec current 22 | V.read v x >>= V.write v x3 23 | V.write v x x1 24 | V.write v current next 25 | return next 26 | {-# INLINE h #-} 27 | 28 | f' xs = runST $ do 29 | v <- V.new n 30 | zipWithM_ (V.write v) xs' (tail xs' ++ [length xs']) 31 | forM_ [length xs .. n - 2] (\i -> V.write v i (i + 1)) 32 | V.write v (n - 1) (head xs') 33 | foldM_ (const . h v) (head xs') $ replicate nIters undefined 34 | r1 <- V.read v 0 35 | r2 <- V.read v r1 36 | return $ (r1+1) * (r2+1) 37 | where 38 | xs' = map (+ (-1)) xs 39 | 40 | g (current, m) = g' $ dec' $ dec current 41 | where 42 | x1 = m ! current 43 | x2 = m ! x1 44 | x3 = m ! x2 45 | next = m ! x3 46 | dec' x = if x == x1 || x == x2 || x == x3 then dec' $ dec x else x 47 | g' x = (next, IM.insert x3 (m ! x) $ IM.insert x x1 $ IM.insert current next m) 48 | 49 | f xs = r1 * r2 50 | where 51 | xs' = map (+ (-1)) xs ++ [length xs .. n - 1] 52 | xs'' = IM.fromList $ zip xs' (tail $ cycle xs') 53 | (r1:r2:_) = map (+1) $ mapToList 0 0 $ snd $ applyN nIters g (head xs', xs'') 54 | mapToList i0 i m = let i' = m ! i in if i' == i0 then [] else i' : mapToList i0 i' m 55 | -------------------------------------------------------------------------------- /24a.hs: -------------------------------------------------------------------------------- 1 | import AOC 2 | 3 | main = interact $ f . parselist (many1 enump) 4 | 5 | data Dir = E | SE | SW | W | NW | NE deriving (Show, Eq, Read, Ord, Bounded, Enum) 6 | 7 | dirToCoord E = ( 1, 0) 8 | dirToCoord W = (-1, 0) 9 | dirToCoord NE = ( 1, 1) 10 | dirToCoord NW = ( 0, 1) 11 | dirToCoord SE = ( 0, -1) 12 | dirToCoord SW = (-1, -1) 13 | 14 | godir z d = z + dirToCoord d 15 | 16 | f xs = length $ filter odd $ map length $ group $ sort $ map (foldl' godir 0) xs 17 | -------------------------------------------------------------------------------- /24b.hs: -------------------------------------------------------------------------------- 1 | import AOC 2 | 3 | main = interact $ f . parselist (many1 enump) 4 | 5 | data Dir = E | SE | SW | W | NW | NE deriving (Show, Eq, Read, Ord, Bounded, Enum) 6 | 7 | dirToCoord E = ( 1, 0) 8 | dirToCoord W = (-1, 0) 9 | dirToCoord NE = ( 1, 1) 10 | dirToCoord NW = ( 0, 1) 11 | dirToCoord SE = ( 0, -1) 12 | dirToCoord SW = (-1, -1) 13 | 14 | godir z d = z + dirToCoord d 15 | 16 | nbs = map dirToCoord [minBound .. maxBound] 17 | rule x ns = let n = count True ns in n == 2 || x && n == 1 18 | 19 | coordsToMap margin zs = [[(x, y) `elem` zs | x <- [minx..maxx]] | y <- [miny..maxy]] 20 | where 21 | (minx, miny) = (minimum $ map fst zs, minimum $ map snd zs) - (margin, margin) 22 | (maxx, maxy) = (maximum $ map fst zs, maximum $ map snd zs) + (margin, margin) 23 | 24 | nIters = 100 25 | 26 | f xs = count True $ elems $ mapnbsN nIters nbs rule False m 27 | where 28 | m = coordsToMap 0 $ map head $ filter (odd . length) $ group $ sort $ map (foldl' godir 0) xs 29 | -------------------------------------------------------------------------------- /25a.hs: -------------------------------------------------------------------------------- 1 | import AOC 2 | 3 | main = interact $ f . map read 4 | 5 | m = 20201227 6 | 7 | f :: [Int] -> Int 8 | f [pub1, pub2] = expMod pub1 priv m 9 | where 10 | priv = discreteLog 7 pub2 m 11 | -------------------------------------------------------------------------------- /2a.hs: -------------------------------------------------------------------------------- 1 | import AOC 2 | 3 | main = interact $ f . parselist p 4 | 5 | p :: Parser (Int, Int, Char, String) 6 | p = do 7 | low <- many1 digit 8 | char '-' 9 | high <- many1 digit 10 | char ' ' 11 | c <- letter 12 | string ": " 13 | s <- many1 letter 14 | return (read low, read high, c, s) 15 | 16 | f xs = count True $ map test xs 17 | 18 | test (low, high, c, s) = let n = count c s 19 | in n >= low && n <= high 20 | -------------------------------------------------------------------------------- /2b.hs: -------------------------------------------------------------------------------- 1 | import AOC 2 | 3 | main = interact $ f . parselist p 4 | 5 | p :: Parser (Int, Int, Char, String) 6 | p = do 7 | low <- many1 digit 8 | char '-' 9 | high <- many1 digit 10 | char ' ' 11 | c <- letter 12 | string ": " 13 | s <- many1 letter 14 | return (read low, read high, c, s) 15 | 16 | f xs = count True $ map test xs 17 | 18 | test (low, high, c, s) = let p1 = s !! (low - 1) 19 | p2 = s !! (high - 1) 20 | in (c == p1) /= (c == p2) 21 | -------------------------------------------------------------------------------- /3a.hs: -------------------------------------------------------------------------------- 1 | import AOC 2 | 3 | main = interact $ f . map (ltov . map (=='#')) 4 | 5 | f m = count True $ f' m 3 0 6 | 7 | f' (m:ms) v x = m !| x : f' ms v (x + v) 8 | f' _ _ _ = [] 9 | -------------------------------------------------------------------------------- /3b.hs: -------------------------------------------------------------------------------- 1 | import AOC 2 | 3 | main = interact $ f . map (ltov . map (=='#')) 4 | 5 | f m = product $ map (f'' m) [(1, 1), (3, 1), (5, 1), (7, 1), (1, 2)] 6 | 7 | f'' m (v, w) = count True $ f' m (v, w - 1) 0 0 8 | 9 | f' (m:ms) (v, w) x 0 = (m !| x) : f' ms (v, w) (x + v) w 10 | f' (_:ms) (v, w) x j = f' ms (v, w) x (j - 1) 11 | f' _ _ _ _ = [] 12 | -------------------------------------------------------------------------------- /4a.hs: -------------------------------------------------------------------------------- 1 | import AOC 2 | import qualified Data.Map as M 3 | 4 | main = interact' $ f . parse p 5 | 6 | data FT = Byr | Iyr | Eyr | Hgt | Hcl | Ecl | Pid | Cid deriving (Show, Eq, Ord, Enum, Bounded) 7 | 8 | field :: Parser (FT, String) 9 | field = do 10 | ft <- enump 11 | char ':' 12 | s <- manyTill anyChar space 13 | return (ft, s) 14 | 15 | p :: Parser [[(FT, String)]] 16 | p = many1 field `sepBy1` char '\n' <* eof 17 | 18 | f (Right ps) = count 7 $ map (M.size . M.delete Cid . M.fromList) ps 19 | -------------------------------------------------------------------------------- /4b.hs: -------------------------------------------------------------------------------- 1 | import AOC 2 | import Data.Char 3 | import qualified Data.Map as M 4 | 5 | main = interact' $ f . parse p 6 | 7 | data FT = Byr | Iyr | Eyr | Hgt | Hcl | Ecl | Pid | Cid deriving (Show, Eq, Ord, Enum, Bounded) 8 | 9 | field :: Parser (FT, String) 10 | field = do 11 | ft <- enump 12 | char ':' 13 | s <- manyTill anyChar space 14 | return (ft, s) 15 | 16 | p :: Parser [[(FT, String)]] 17 | p = many1 field `sepBy1` char '\n' <* eof 18 | 19 | f (Right ps) = count True . map isValid . filter ((==7) . M.size) . map (M.delete Cid . M.fromList) $ ps 20 | 21 | hgtp :: Parser (Int, String) 22 | hgtp = (,) . read <$> many1 digit <*> many1 anyChar 23 | 24 | isValid p = 25 | let 26 | byr = read (p M.! Byr) :: Int 27 | iyr = read (p M.! Iyr) :: Int 28 | eyr = read (p M.! Eyr) :: Int 29 | hgt = parse hgtp $ p M.! Hgt 30 | hgtok = case hgt of 31 | Left _ -> False 32 | Right (hgt, hgtu) -> case hgtu of 33 | "in" -> hgt >= 59 && hgt <= 76 34 | "cm" -> hgt >= 150 && hgt <= 193 35 | _ -> False 36 | (h1:hcl) = p M.! Hcl 37 | ecl = p M.! Ecl 38 | pid = p M.! Pid 39 | in 40 | and [ byr >= 1920, byr <= 2002 41 | , iyr >= 2010, iyr <= 2020 42 | , eyr >= 2020, eyr <= 2030 43 | , hgtok 44 | , h1 == '#', length hcl == 6, all (`elem` "0123456789abcdef") hcl 45 | , ecl `elem` ["amb", "blu", "brn", "gry", "grn", "hzl", "oth"] 46 | , length pid == 9, all isDigit pid 47 | ] 48 | -------------------------------------------------------------------------------- /5a.hs: -------------------------------------------------------------------------------- 1 | import AOC 2 | 3 | main = interact $ maximum . mapMaybe (readBin . tr "FBLR" "0101") 4 | -------------------------------------------------------------------------------- /5b.hs: -------------------------------------------------------------------------------- 1 | import AOC 2 | 3 | main = interact $ g . sort . mapMaybe (readBin . tr "FBLR" "0101") 4 | 5 | g xs = head [succ x | (x, y) <- zip xs (tail xs), succ x /= y] 6 | -------------------------------------------------------------------------------- /6a.hs: -------------------------------------------------------------------------------- 1 | import AOC 2 | 3 | main = interactg $ sum . map (length . nub . concat) 4 | -------------------------------------------------------------------------------- /6b.hs: -------------------------------------------------------------------------------- 1 | import AOC 2 | import qualified Data.Set as S 3 | 4 | main = interactg $ sum . map (S.size . foldl1' S.intersection . map S.fromList) 5 | -------------------------------------------------------------------------------- /7a.hs: -------------------------------------------------------------------------------- 1 | import AOC 2 | 3 | main = interact $ f . parselist p 4 | 5 | type Bag = Int 6 | 7 | p :: Parser (Bag, [(Int, Bag)]) 8 | p = do 9 | b <- bag 10 | string " contain " 11 | bs <- (string "no other bags" >> return []) <|> (bags `sepBy1` string ", ") 12 | char '.' 13 | return (b, bs) 14 | 15 | bag :: Parser Bag 16 | bag = do 17 | d1 <- many1 letter 18 | char ' ' 19 | d2 <- many1 letter 20 | string " bag" 21 | optional $ char 's' 22 | return $ hash $ d1 ++ ' ':d2 23 | 24 | bags :: Parser (Int, Bag) 25 | bags = do 26 | n <- read <$> many1 digit 27 | char ' ' 28 | b <- bag 29 | return (n, b) 30 | 31 | f bs = length (converge containedByAny [hash "shiny gold"]) - 1 32 | where 33 | containedByAny bs' = nub $ bs' ++ map fst (filter (matchAny bs') bs) 34 | matchAny xs (_, ys) = not $ null [undefined | x <- xs, (_, y) <- ys, x == y] 35 | -------------------------------------------------------------------------------- /7b.hs: -------------------------------------------------------------------------------- 1 | import AOC 2 | import Data.Maybe 3 | import qualified Data.Map as M 4 | 5 | main = interact $ f . parselist p 6 | 7 | type Bag = Int 8 | 9 | p :: Parser (Bag, [(Int, Bag)]) 10 | p = do 11 | b <- bag 12 | string " contain " 13 | bs <- (string "no other bags" >> return []) <|> (bags `sepBy1` string ", ") 14 | char '.' 15 | return (b, bs) 16 | 17 | bag :: Parser Bag 18 | bag = do 19 | d1 <- many1 letter 20 | char ' ' 21 | d2 <- many1 letter 22 | string " bag" 23 | optional $ char 's' 24 | return $ hash $ d1 ++ ' ':d2 25 | 26 | bags :: Parser (Int, Bag) 27 | bags = do 28 | n <- read <$> many1 digit 29 | char ' ' 30 | b <- bag 31 | return (n, b) 32 | 33 | f bs = summarize (map fst bs, (M.fromList bs M.!)) (sum . map (\(i, v) -> i * (v + 1))) $ hash "shiny gold" 34 | -------------------------------------------------------------------------------- /8a.hs: -------------------------------------------------------------------------------- 1 | import AOC 2 | import qualified Data.Vector as V 3 | import qualified Data.Set as S 4 | 5 | main = interact $ f . ltov . parselist p 6 | 7 | data Instruction = Acc | Jmp | Nop deriving (Show, Eq, Read, Ord, Bounded, Enum) 8 | 9 | p :: Parser (Instruction, Int) 10 | p = do 11 | instr <- enump 12 | space 13 | sgn <- choice [char '+' >> return 1, char '-' >> return (-1), return 1] 14 | arg <- read <$> many1 digit 15 | return (instr, sgn * arg) 16 | 17 | f :: Vector (Instruction, Int) -> Int 18 | f prg = exec 0 0 S.empty 19 | where 20 | exec a ip s = 21 | if ip `S.member` s 22 | then 23 | a 24 | else 25 | let 26 | s' = S.insert ip s 27 | ip' = succ ip 28 | in 29 | case prg V.!? ip of 30 | Just (Acc, i) -> exec (a + i) ip' s' 31 | Just (Jmp, i) -> exec a (ip + i) s' 32 | Just (Nop, _) -> exec a ip' s' 33 | -------------------------------------------------------------------------------- /8b.hs: -------------------------------------------------------------------------------- 1 | import AOC 2 | import Control.Monad.State 3 | import qualified Data.Vector as V 4 | import qualified Data.Set as S 5 | 6 | main = interact $ f . ltov . parselist p 7 | 8 | data Instruction = Acc | Jmp | Nop deriving (Show, Eq, Read, Ord, Bounded, Enum) 9 | 10 | p :: Parser (Instruction, Int) 11 | p = do 12 | instr <- enump 13 | space 14 | sgn <- choice [char '+' >> return 1, char '-' >> return (-1), return 1] 15 | arg <- read <$> many1 digit 16 | return (instr, sgn * arg) 17 | 18 | mapAt i f v = v V.// [(i, f $ v V.! i)] 19 | 20 | f prg = head $ catMaybes $ do 21 | i <- [0..] 22 | return $ f' $ mapAt i change prg 23 | where 24 | change (Nop, j) = (Jmp, j) 25 | change (Jmp, j) = (Nop, j) 26 | change x = x 27 | 28 | f' :: Vector (Instruction, Int) -> Maybe Int 29 | f' prg = case runState exec (0, 0, S.empty) of 30 | (False, (a, _, _)) -> Just a 31 | _ -> Nothing 32 | where 33 | exec = do 34 | (a, ip, s) <- get 35 | if ip `S.member` s 36 | then 37 | return True 38 | else do 39 | let 40 | s' = S.insert ip s 41 | ip' = succ ip 42 | case prg V.!? ip of 43 | Nothing -> return False 44 | Just op -> do 45 | case op of 46 | (Acc, i) -> put (a + i, ip', s') 47 | (Jmp, i) -> put (a, ip + i, s') 48 | (Nop, _) -> put (a, ip', s') 49 | exec 50 | -------------------------------------------------------------------------------- /9a.hs: -------------------------------------------------------------------------------- 1 | import AOC 2 | 3 | main = interact $ f . map read 4 | 5 | f :: [Int] -> Int 6 | f xs = f' (take 25 xs) (drop 25 xs) 7 | 8 | f' (x:xs) (y:ys) = if t y (x:xs) then f' (xs ++ [y]) ys else y 9 | 10 | t y (x:xs) = y - x `elem` xs || t y xs 11 | t y [] = False 12 | -------------------------------------------------------------------------------- /9b.hs: -------------------------------------------------------------------------------- 1 | import AOC 2 | 3 | main = interact $ g . map read 4 | 5 | g :: [Int] -> Int 6 | g xs = let n = f xs 7 | xs' = h n xs 8 | in maximum xs' + minimum xs' 9 | 10 | h n xs = head $ filter ((==n) . sum) $ concatMap tails $ inits xs 11 | 12 | f xs = f' (take 25 xs) (drop 25 xs) 13 | 14 | f' (x:xs) (y:ys) = if t y (x:xs) then f' (xs ++ [y]) ys else y 15 | 16 | t y (x:xs) = y - x `elem` xs || t y xs 17 | t y [] = False 18 | -------------------------------------------------------------------------------- /AOC.hs: -------------------------------------------------------------------------------- 1 | {-# LANGUAGE GeneralizedNewtypeDeriving #-} 2 | {-# LANGUAGE ScopedTypeVariables #-} 3 | {-# LANGUAGE TupleSections #-} 4 | {-# LANGUAGE TypeFamilies #-} 5 | {-# OPTIONS_HADDOCK prune, ignore-exports #-} 6 | {-| 7 | Module : AOC 8 | Description : A library of useful functions for solving coding problems 9 | Copyright : (c) 2021 Haskell Coder 10 | License : GPL-3 11 | Maintainer : haskelling@pdr.cx 12 | Stability : experimental 13 | Portability : POSIX 14 | 15 | AOC is a library of useful functions for solving coding problems. 16 | 17 | It accompanies a [video series](https://www.youtube.com/playlist?list=PLDRIsR-OaZkzqqyss1B01G_7RWuXnUeb5) 18 | describing how to solve the [2021 Advent of Code challenges](https://www.adventofcode.com/2021). 19 | It is intended as a learning tool for beginner and intermediate Haskellers, so 20 | often goes into some depth describing Haskell concepts, tools, and library 21 | functions. 22 | 23 | The code for this module along with the 2021 AoC solutions can be cloned from [GitHub](https://github.com/haskelling/aoc2021). 24 | -} 25 | module AOC(module Prelude, module AOC, module Text.Parsec, module Data.Vector, module Data.Char, module Data.List, module Data.List.Split, module Data.List.Extra, module Data.Hashable, module Data.Maybe, module Data.Either, module Data.Bool, module Control.Monad, module Text.Parsec.Expr, module Control.Arrow) where 26 | 27 | import Control.Arrow 28 | import Control.Exception (ArithException (..)) 29 | import Control.Monad 30 | import Data.Bits 31 | import Data.Bool 32 | import Data.Char 33 | import Data.Either 34 | import Data.Hashable (hash) 35 | import Data.IntMap (IntMap) 36 | import qualified Data.IntMap as IM 37 | import Data.List hiding (nub) 38 | import Data.List.Split hiding (endBy, oneOf, sepBy) 39 | import Data.List.Extra hiding (splitOn, merge, chunksOf, linesBy, wordsBy, lower, upper, split, nub) 40 | import qualified Data.Map as M 41 | import Data.Map.Merge.Strict 42 | import qualified Data.Map.Strict as MS 43 | import Data.Maybe 44 | import qualified Data.Set as S 45 | import Data.Tuple 46 | import Data.Vector (Vector, imap) 47 | import qualified Data.Vector as V 48 | import Data.Vector.Unboxed (Unbox) 49 | import qualified Data.Vector.Unboxed as U 50 | import Numeric 51 | import Prelude hiding (interact) 52 | import qualified Prelude 53 | import Text.Parsec hiding (count, parse, uncons) 54 | import qualified Text.Parsec as Parsec 55 | import Text.Parsec.Expr 56 | 57 | 58 | -- * Enhanced interact functions 59 | 60 | -- | The 'interact' function replaces 'Prelude.interact'. It reads from stdin 61 | -- and splits the input into 'lines'. It uses the given function to turn the 62 | -- resulting list of 'String's into a 'Show'able value. It 'show's the value 63 | -- and sends it to stdout with an added newline. 64 | -- 65 | -- >>> sumValuesProg = interact (sum . map read) 66 | -- 67 | interact :: Show a => ([String] -> a) -> IO () 68 | interact f = interact' $ f . lines 69 | 70 | -- | The 'interact'' function reads from stdin and uses the given function to 71 | -- run the resulting 'String' into a 'Show'able value. It 'show's the value and 72 | -- sends it to stdout with an added newline. 73 | -- 74 | -- >>> fileSizeProg = interact' length 75 | -- 76 | interact' :: Show a => (String -> a) -> IO () 77 | interact' f = Prelude.interact $ (++"\n") . show . f 78 | 79 | -- | The 'interactg' function will not only split by 'lines', like 'interact', 80 | -- but also splits these into groups separated by blank lines. Therefore, the 81 | -- given function must accept a list of list of 'String's. 82 | -- 83 | -- >>> countParagraphsProg = interactg length 84 | -- 85 | interactg :: Show a => ([[String]] -> a) -> IO () 86 | interactg f = interact $ f. splitOn [""] 87 | 88 | 89 | -- * Parsing, Reading and Showing 90 | 91 | -- ** Parsing 92 | 93 | -- | 'Parser' is a convenience type for 'Parsec' 94 | type Parser = Parsec String () 95 | 96 | -- | The 'parse' function is a convenience function for 'Parsec.parse' that 97 | -- removes the requirement to provide a file name. 98 | parse :: Parser a -- ^ The parser for "a"s 99 | -> String -- ^ The string to be parsed 100 | -> Either ParseError a -- ^ The successfully parsed value or an error 101 | parse p = Parsec.parse p "" 102 | 103 | -- | The 'parselist' function parses a list of 'String's using 'parse' and 104 | -- returns the list of parsed "a"s. If any parse was unsuccessful we crash the 105 | -- program, showing the first error encountered. 106 | parselist :: Parser a -- ^ The parser for "a"s 107 | -> [String] -- ^ The list of 'String's to parse 108 | -> [a] -- ^ The resulting list of "a"s 109 | parselist p = either (error . show) id . mapM (parse p) 110 | 111 | -- | The 'chari' function is a case-insensitive 'Parser' for the given 'Char'. 112 | -- It uses 'toLower' and 'toUpper' on the given 'Char' to test the input with. 113 | -- 114 | -- >>> parse (chari 'e') "E" 115 | -- Right 'E' 116 | -- 117 | chari :: Char -> Parser Char 118 | chari c = oneOf [toLower c, toUpper c] 119 | 120 | -- | The 'stringi' function is a case-insensitive 'Parser' for the given 121 | -- 'String'. 122 | -- 123 | -- >>> parse (stringi "HeLlO") "Hello world!" 124 | -- Right "Hello" 125 | -- 126 | stringi :: String -> Parser String 127 | stringi = mapM chari 128 | 129 | -- | The 'enump' function is a case-insensitive 'Parser' for any 'Bounded' 130 | -- 'Enum'. 131 | -- 132 | -- >>> data Primary = Red | Green | Blue deriving (Show, Enum, Bounded) 133 | -- >>> parselist enump $ words "red green red blue" :: [Primary] 134 | -- [Red,Green,Red,Blue] 135 | -- 136 | enump :: forall b. (Enum b, Bounded b, Show b) => Parser b 137 | enump = choice $ map sr [minBound :: b .. maxBound :: b] 138 | where 139 | sr :: (Show b) => b -> Parser b 140 | sr x = try $ stringi (show x) >> return x 141 | 142 | -- | The 'integer function is a 'Parser' for unsigned 'Int's. 143 | -- 144 | -- >>> parse integer "301" 145 | -- Right 301 146 | -- 147 | integer :: Parser Int 148 | integer = read <$> many1 digit 149 | 150 | -- ** Reading 151 | 152 | -- |The 'readBin' function reads a binary number from a String. 153 | -- Any non-binary digit encountered will result in a Nothing. 154 | -- 155 | -- >>> readBin "01011010" 156 | -- Just 90 157 | -- 158 | readBin :: ReadBin a => [a] -> Maybe Int 159 | readBin = foldl' add (Just 0) 160 | where 161 | add x y = do 162 | x' <- x 163 | y' <- toBin y 164 | return $ x' * 2 + y' 165 | 166 | class ReadBin a where 167 | toBin :: a -> Maybe Int 168 | 169 | instance ReadBin Char where 170 | toBin '0' = Just 0 171 | toBin '1' = Just 1 172 | toBin _ = Nothing 173 | 174 | instance ReadBin Bool where 175 | toBin False = Just 0 176 | toBin True = Just 1 177 | 178 | newtype Bin = Bin { unBin :: Int } deriving (Eq, Ord, Enum, Bounded, Num, Bits) 179 | 180 | instance Show Bin where 181 | showsPrec _ (Bin i) = showIntAtBase 2 intToDigit i 182 | 183 | instance Read Bin where 184 | readsPrec _ s = let (x, y) = span (`elem` "01") s in [(Bin $ fromJust $ readBin x, y)] 185 | 186 | -- ** Showing 187 | 188 | -- |A newtype for String whose show implementation doesn't add quotes. 189 | -- 190 | -- >>> Str "abc" 191 | -- abc 192 | -- 193 | newtype Str = Str String deriving (Eq, Ord, Read) 194 | instance Show Str where 195 | show (Str s) = s 196 | 197 | 198 | -- * List functions 199 | 200 | -- | The 'count' function returns the number of occurrences of the given value 201 | -- in the given list. 202 | -- 203 | -- >>> count 'e' "Advent of Code 2021" 204 | -- 2 205 | -- 206 | -- >>> count 2 [3,2,1,0,4,2,3,4,2] 207 | -- 3 208 | -- 209 | count :: Eq a 210 | => a -- ^ The value to look for 211 | -> [a] -- ^ The list to look in 212 | -> Int -- ^ The number of times the value is found in the list 213 | count c = length . filter (==c) 214 | 215 | -- |The 'tr' function translates lists according to a given mapping. 216 | -- 217 | -- >>> tr "LR" "01" "LALR" 218 | -- "0A01" 219 | -- 220 | tr :: Ord a 221 | => [a] -- ^ The "from" part of the mapping 222 | -> [a] -- ^ The "to" part of the mapping 223 | -> [a] -- ^ The original list 224 | -> [a] -- ^ The updated list after replacing "from" elements with their "to" counterparts 225 | tr xs ys = map (\x -> fromMaybe x $ M.fromList (zip xs ys) M.!? x) 226 | 227 | 228 | -- * Vector functions 229 | 230 | -- | The '!|' operator indexes into a 'Vector' modulo its length. This will 231 | -- crash with a 'DivideByZero' 'ArithException' if the 'Vector' is empty. O(1) 232 | -- 233 | -- >>> ltov [0..99] !| 254375 234 | -- 75 235 | -- 236 | (!|) :: Vector a -> Int -> a 237 | v !| i = v V.! (i `mod` V.length v) 238 | 239 | -- | The 'ltov' function is a convenience function for 'Vector.fromList'. 240 | ltov :: [a] -> Vector a 241 | ltov = V.fromList 242 | 243 | -- | The 'ltov2' function converts a list of lists into a 'Vector' of 'Vector's. 244 | ltov2 :: [[a]] -> Vector (Vector a) 245 | ltov2 = ltov . map ltov 246 | 247 | -- | The 'ltov3' function converts a list of lists of lists into a 'Vector' of 'Vector's of 'Vector's. 248 | ltov3 :: [[[a]]] -> Vector (Vector (Vector a)) 249 | ltov3 = ltov . map ltov2 250 | 251 | -- | The 'ltov4' function converts a list of lists of lists of lists into a 'Vector' of 'Vector's of 'Vector's of 'Vector's. 252 | ltov4 :: [[[[a]]]] -> Vector (Vector (Vector (Vector a))) 253 | ltov4 = ltov . map ltov3 254 | 255 | -- | The 'vtol' function is a convenience function for 'Vector.toList'. 256 | vtol :: Vector a -> [a] 257 | vtol = V.toList 258 | 259 | -- | The 'vtol2' function converts a 'Vector' of 'Vector's into a list of lists. 260 | vtol2 :: Vector (Vector a) -> [[a]] 261 | vtol2 = map vtol . vtol 262 | 263 | -- | The 'vtol2' function converts a 'Vector' of 'Vector's of 'Vector's into a list of lists of lists. 264 | vtol3 :: Vector (Vector (Vector a)) -> [[[a]]] 265 | vtol3 = map vtol2 . vtol 266 | 267 | -- | The 'vtol2' function converts a 'Vector' of 'Vector's of 'Vector's of 'Vector's into a list of lists of lists of lists. 268 | vtol4 :: Vector (Vector (Vector (Vector a))) -> [[[[a]]]] 269 | vtol4 = map vtol3 . vtol 270 | 271 | 272 | -- * Algorithms 273 | 274 | -- ** Directed Acyclic Graph Algorithms 275 | 276 | -- |The 'summarize' function does a bottom-up calculation on a directed 277 | -- acyclic graph (DAG) by running a summary function on each node. 278 | -- 279 | -- >>> f [] = 1; f xs = sum $ map snd xs 280 | -- >>> summarize ([1..10], \x -> [(0, y) | y <- [2*x, 3*x..10]]) f 1 281 | -- 13 282 | -- 283 | -- >>> f [] = 1; f xs = sum $ map (\(w, s) -> w * s) xs 284 | -- >>> summarize ([1..10], \x -> [(y, y) | y <- [2*x, 3*x..10]]) f 1 285 | -- 279 286 | -- 287 | summarize :: Ord n 288 | => ([n], n -> [(v, n)]) -- ^ The list of nodes and function from node to list of children, given as a tuple of edge "weight" and child node 289 | -> ([(v, w)] -> w) -- ^ Summary function to populate the summary value for each node given a list of tuples representing the edge "weight" and summary value for each child node 290 | -> n -- ^ The node for which we need the summary 291 | -> w -- ^ The resulting summary value 292 | summarize (nodes, children) f = (m M.!) 293 | where 294 | m = M.fromSet (f . map2 (m M.!) . children) $ S.fromList nodes 295 | 296 | -- ** Maths Functions 297 | 298 | discreteLog :: Int -> Int -> Int -> Int 299 | discreteLog n x m = p - (xs IM.! k) 300 | where 301 | s = ceiling (sqrt (fromIntegral m) :: Double) 302 | xs = IM.fromList [(((x `mod` m) * expMod n r m) `mod` m, r) | r <- [0 .. s]] 303 | ys = IM.fromList [(expMod n ((s -1) * r) m, (s -1) * r) | r <- [1 .. s]] 304 | (k, p) = head $ IM.toList $ IM.filterWithKey (\k_ _ -> IM.member k_ xs) ys 305 | 306 | expMod :: Int -> Int -> Int -> Int 307 | expMod 0 _ _ = 0 308 | expMod _ 0 _ = 1 309 | expMod x e m 310 | | even e = let p = expMod x (e `div` 2) m in mo $! p * p 311 | | otherwise = mo $! x * expMod x (e - 1) m 312 | where mo = flip mod m 313 | 314 | -- ** General-Purpose Functions 315 | 316 | -- | Replaces the 'nub' function from Data.List with a faster version that also sorts the list. 317 | nub :: Ord a => [a] -> [a] 318 | nub = map head . group . sort 319 | 320 | -- | The 'map2' function is simply 'fmap' '.' 'fmap'. 321 | map2 :: (Functor f, Functor g) => (a -> b) -> f (g a) -> f (g b) 322 | map2 = fmap . fmap 323 | 324 | -- |The 'converge' function repeatedly applies f until there's no change 325 | -- in the output. That is, it calculates \( f (f (f ... (f x))) \). 326 | converge :: Eq a => (a -> a) -> a -> a 327 | converge f x = let x' = f x in if x' == x then x else converge f x' 328 | 329 | -- |The 'applyN' function applies f n times. 330 | -- 331 | -- >>> applyN 5 (+2) 3 332 | -- 13 333 | -- 334 | applyN n = foldr (.) id . replicate n 335 | 336 | -- ** Grid Algorithms 337 | 338 | type GridUV2 a = (Int, U.Vector a) 339 | 340 | ltouv2 :: Unbox a => [[a]] -> GridUV2 a 341 | ltouv2 = length . head &&& U.fromList . concat 342 | 343 | uvtol2 :: Unbox a => GridUV2 a -> [[a]] 344 | uvtol2 (w, v) = chunksOf w $ U.toList v 345 | 346 | mapnbsuv :: (Unbox a, Unbox b) 347 | => [(Int, Int)] -- ^ The list of coordinate offsets 348 | -> (a -> [a] -> b) -- ^ The mapping function 349 | -> GridUV2 a -- ^ The original grid 350 | -> GridUV2 b -- ^ The updated grid 351 | mapnbsuv nbs f (w, v) = (w, U.fromList $ modify 0 0 $ U.toList v) 352 | where 353 | modify _ _ [] = [] 354 | modify i j xs | i == w = modify 0 (j + 1) xs 355 | modify i j (x:xs) = f x (mapMaybe (get (i, j)) nbs):modify (i + 1) j xs 356 | get z0 z = if x' < 0 || x' >= w || y' < 0 then Nothing else v U.!? (y' * w + x') 357 | where 358 | (x', y') = z0 + z 359 | 360 | type Grid2 a = MS.Map (Int, Int) a 361 | 362 | ltog2 :: [[a]] -> Grid2 a 363 | ltog2 = MS.fromList . concat . zipWith (\j -> zipWith (\i -> ((i, j),)) [0..]) [0..] 364 | 365 | gtol2 :: a -> Grid2 a -> [[a]] 366 | gtol2 d m = [[fromMaybe d (m MS.!? (x, y)) | x <- [minimum xs .. maximum xs]] | y <- [minimum ys .. maximum ys]] 367 | where 368 | (xs, ys) = unzip $ MS.keys m 369 | 370 | type Grid3 a = MS.Map (Int, Int, Int) a 371 | 372 | ltog3 :: [[[a]]] -> Grid3 a 373 | ltog3 = MS.fromList . concat . zipWith (\k -> concat . zipWith (\j -> zipWith (\i -> ((i, j, k),)) [0..]) [0..]) [0..] 374 | 375 | gtol3 :: a -> Grid3 a -> [[[a]]] 376 | gtol3 d m = [[[fromMaybe d (m MS.!? (x, y, z)) | x <- [minimum xs .. maximum xs]] | y <- [minimum ys .. maximum ys]] | z <- [minimum zs .. maximum zs]] 377 | where 378 | (xs, ys, zs) = unzip3 $ MS.keys m 379 | 380 | type Grid4 a = MS.Map (Int, Int, Int, Int) a 381 | 382 | ltog4 :: [[[[a]]]] -> Grid4 a 383 | ltog4 = MS.fromList . concat . zipWith (\l -> concat . zipWith (\k -> concat . zipWith (\j -> zipWith (\i -> ((i, j, k, l),)) [0..]) [0..]) [0..]) [0..] 384 | 385 | gtol4 :: a -> Grid4 a -> [[[[a]]]] 386 | gtol4 d m = [[[[fromMaybe d (m MS.!? (w, x, y, z)) | w <- [minimum ws .. maximum ws]] | x <- [minimum xs .. maximum xs]] 387 | | y <- [minimum ys .. maximum ys]] | z <- [minimum zs .. maximum zs]] 388 | where 389 | (ws, xs, ys, zs) = unzip4 $ MS.keys m 390 | 391 | mapnbsg :: (Eq a, Num ix, Ord ix) 392 | => [ix] -- ^ The list of coordinate offsets 393 | -> (a -> [a] -> a) -- ^ The mapping function 394 | -> a -- ^ The value of an empty cell 395 | -> MS.Map ix a -- ^ The original grid 396 | -> MS.Map ix a -- ^ The updated grid 397 | mapnbsg nbs f d m = merge (mapMaybeMissing $ \_ x -> f' x []) 398 | (mapMaybeMissing $ const $ f' d) 399 | (zipWithMaybeMatched $ const f') 400 | m m' 401 | where 402 | m' = M.fromListWith (++) [(x + n, [v]) | (x, v) <- M.toList m, n <- nbs] 403 | f' x xs = let x' = f x xs in if x' == d then Nothing else Just x' 404 | 405 | mapnbsv :: [(Int, Int)] -- ^ The list of coordinate offsets 406 | -> (a -> [a] -> b) -- ^ The mapping function 407 | -> Vector (Vector a) -- ^ The original grid 408 | -> Vector (Vector b) -- ^ The updated grid 409 | mapnbsv nbs f m = imap (\y v -> imap (\x i -> modify i (x, y)) v) m 410 | where 411 | modify i x = f i $ mapMaybe (get x) nbs 412 | get (x0, y0) (x, y) = do 413 | row <- m V.!? (y0 + y) 414 | row V.!? (x0 + x) 415 | 416 | -- |The 'mapnbs' function maps a function over a 'List' of 'List's, 417 | -- treating it as a grid of cells. 418 | -- Given a list of coordinate offsets, the mapping function is provided the 419 | -- cell value, and a list of the values of the cells at those offsets. 420 | -- 421 | -- >>> mapnbs nbs8 conwayRule False $ replicate 5 $ replicate 5 True 422 | -- [[False,False,True,True,True,False,False],[False,True,False,False,False,True,False],[True,False,False,False,False,False,True],[True,False,False,False,False,False,True],[True,False,False,False,False,False,True],[False,True,False,False,False,True,False],[False,False,True,True,True,False,False]] 423 | -- 424 | -- >>> mapnbs nbs4 conwayRule False $ replicate 5 $ replicate 5 True 425 | -- [[True,True,True,True,True],[True,False,False,False,True],[True,False,False,False,True],[True,False,False,False,True],[True,True,True,True,True]] 426 | -- 427 | mapnbs :: Eq a 428 | => [(Int, Int)] -- ^ The list of coordinate offsets 429 | -> (a -> [a] -> a) -- ^ The mapping function 430 | -> a -- ^ The value of an empty cell 431 | -> [[a]] -- ^ The original grid 432 | -> [[a]] -- ^ The updated grid 433 | mapnbs nbs f d = gtol2 d . mapnbsg nbs f d . ltog2 434 | 435 | mapnbsC :: (Unbox a, Eq a) 436 | => [(Int, Int)] -- ^ The list of coordinate offsets 437 | -> (a -> [a] -> a) -- ^ The mapping function 438 | -> [[a]] -- ^ The original grid 439 | -> [[a]] -- ^ The updated grid 440 | mapnbsC nbs f = uvtol2 . converge (mapnbsuv nbs f) . ltouv2 441 | 442 | mapnbsN :: Eq a 443 | => Int -- ^ The number of iterations 444 | -> [(Int, Int)] -- ^ The list of coordinate offsets 445 | -> (a -> [a] -> a) -- ^ The mapping function 446 | -> a -- ^ The value of an empty cell 447 | -> [[a]] -- ^ The original grid 448 | -> Grid2 a -- ^ The updated grid 449 | mapnbsN n nbs f d = applyN n (mapnbsg nbs f d) . ltog2 450 | 451 | -- |The 'mapnbs3' function is the 3-d variant of 'mapnbs'. 452 | mapnbs3 :: Eq a 453 | => [(Int, Int, Int)] -- ^ The list of coordinate offsets 454 | -> (a -> [a] -> a) -- ^ The mapping function 455 | -> a -- ^ The value of an empty cell 456 | -> [[[a]]] -- ^ The original grid 457 | -> Grid3 a -- ^ The updated grid 458 | mapnbs3 nbs f d = mapnbsg nbs f d . ltog3 459 | 460 | mapnbs3N :: Eq a 461 | => Int -- ^ The number of iterations 462 | -> [(Int, Int, Int)] -- ^ The list of coordinate offsets 463 | -> (a -> [a] -> a) -- ^ The mapping function 464 | -> a -- ^ The value of an empty cell 465 | -> [[[a]]] -- ^ The original grid 466 | -> Grid3 a -- ^ The updated grid 467 | mapnbs3N n nbs f d = applyN n (mapnbsg nbs f d) . ltog3 468 | 469 | -- |The 'mapnbs4' function is the 4-d variant of 'mapnbs'. 470 | mapnbs4 :: Eq a 471 | => [(Int, Int, Int, Int)] -- ^ The list of coordinate offsets 472 | -> (a -> [a] -> a) -- ^ The mapping function 473 | -> a -- ^ The value of an empty cell 474 | -> [[[[a]]]] -- ^ The original grid 475 | -> Grid4 a -- ^ The updated grid 476 | mapnbs4 nbs f d = mapnbsg nbs f d . ltog4 477 | 478 | mapnbs4N :: Eq a 479 | => Int -- ^ The number of iterations 480 | -> [(Int, Int, Int, Int)] -- ^ The list of coordinate offsets 481 | -> (a -> [a] -> a) -- ^ The mapping function 482 | -> a -- ^ The value of an empty cell 483 | -> [[[[a]]]] -- ^ The original grid 484 | -> Grid4 a -- ^ The updated grid 485 | mapnbs4N n nbs f d = applyN n (mapnbsg nbs f d) . ltog4 486 | 487 | elems = MS.elems 488 | 489 | -- |The 'maplos' function maps a function over a 'Vector' of 'Vector's, 490 | -- treating it as a grid of cells. 491 | -- A coordinate list is supplied and the given predicate determines what is 492 | -- considered an empty cell. The mapping function is provided the cell value, 493 | -- and a list of cell values that are in the line of sight, in the direction of 494 | -- the given coordinates. 495 | -- 496 | -- >>> maplos nbs8 not conwayRule $ ltov2 $ replicate 5 $ replicate 5 True 497 | -- [[True,False,False,False,True],[False,False,False,False,False],[False,False,False,False,False],[False,False,False,False,False],[True,False,False,False,True]] 498 | -- 499 | -- >>> maplos nbs4 not conwayRule $ ltov2 $ replicate 5 $ replicate 5 True 500 | -- [[True,True,True,True,True],[True,False,False,False,True],[True,False,False,False,True],[True,False,False,False,True],[True,True,True,True,True]] 501 | -- 502 | maplos :: [(Int, Int)] -- ^ The list of coordinates indicating the line-of-sight directions 503 | -> (a -> Bool) -- ^ The isEmpty predicate - line of sight continues through cells whose value returns 'True' 504 | -> (a -> [a] -> b) -- ^ The mapping function, given the cell value and the values of all cells found through a line-of-sight search 505 | -> Vector (Vector a) -- ^ The original grid 506 | -> Vector (Vector b) -- ^ The updated grid 507 | maplos nbs isEmpty f m = imap (\y v -> imap (\x i -> modify i (x, y)) v) m 508 | where 509 | modify i x = f i $ mapMaybe (getFirst x) nbs 510 | getFirst x0 x = do 511 | v <- get x0 x 512 | if isEmpty v then getFirst (x0 + x) x else return v 513 | get (x0, y0) (x, y) = do 514 | row <- m V.!? (y0 + y) 515 | row V.!? (x0 + x) 516 | 517 | maplosC :: Eq a 518 | => [(Int, Int)] -- ^ The list of coordinates indicating the line-of-sight directions 519 | -> (a -> Bool) -- ^ The isEmpty predicate - line of sight continues through cells whose value returns 'True' 520 | -> (a -> [a] -> a) -- ^ The mapping function, given the cell value and the values of all cells found through a line-of-sight search 521 | -> [[a]] -- ^ The original grid 522 | -> [[a]] -- ^ The updated grid 523 | maplosC nbs p f m = vtol2 $ converge (maplos nbs p f) $ ltov2 m 524 | 525 | nbs4, nbs8 :: [(Int, Int)] 526 | -- |'nbs4' lists the offsets of the four non-diagonal neighbours of a cell 527 | -- in a grid. 528 | nbs4 = [(0, 1), (-1, 0), (1, 0), (0, -1)] 529 | -- |'nbs8' lists the offsets of the eight neighbours of a cell in a grid. 530 | nbs8 = [(-1, 1), (0, 1), (1, 1), (-1, 0), (1, 0), (-1, -1), (0, -1), (1, -1)] 531 | 532 | nbs6, nbs26 :: [(Int, Int, Int)] 533 | -- |3-d equivalent of 'nbs4' 534 | nbs6 = [(0, 0, 1), (0, -1, 0), (0, 1, 0), (0, 0, -1), (1, 0, 0), (-1, 0, 0)] 535 | -- |3-d equivalent of 'nbs8' 536 | nbs26 = [(x, y, z) | x <- [-1..1], y <- [-1..1], z <- [-1..1], (x, y, z) /= (0, 0, 0)] 537 | 538 | nbs8_4, nbs80 :: [(Int, Int, Int, Int)] 539 | -- |3-d equivalent of 'nbs4' 540 | nbs8_4 = [(0, 0, 0, 1), (0, 0, -1, 0), (0, 0, 1, 0), (0, 0, 0, -1), 541 | (0, 1, 0, 0), (0, -1, 0, 0), (1, 0, 0, 0), (-1, 0, 0, 0)] 542 | -- |3-d equivalent of 'nbs8' 543 | nbs80 = [(x, y, z, w) | x <- [-1..1], y <- [-1..1], z <- [-1..1], w <- [-1..1], (x, y, z, w) /= (0, 0, 0, 0)] 544 | 545 | -- |The 'conwayRule' function is an implementation of the rule followed by the 546 | -- cells in Conway's Game of Life. It can be used with the 'map8nbs' function 547 | -- to model the original version of the game. 548 | -- 549 | -- >>> conwayRule True [True, False, True, False, True, True, False, False] 550 | -- False 551 | -- 552 | conwayRule :: Bool -- ^ The cell's current state 553 | -> [Bool] -- ^ The current states of the cell's neighbours 554 | -> Bool -- ^ The cell's next state 555 | conwayRule x ns = let n = count True ns in n == 3 || x && n == 2 556 | 557 | -- ** Coordinate calculations 558 | 559 | -- *** 2-D space 560 | 561 | -- |'Num' instance for 2-tuples 562 | instance (Num a, Num b) => Num (a, b) where 563 | (x, y) + (u, v) = (x + u, y + v) 564 | (x, y) * (u, v) = (x * u, y * v) 565 | negate (x, y) = (negate x, negate y) 566 | fromInteger x = (fromInteger x, 0) 567 | abs (x, y) = (abs x, abs y) 568 | signum (x, y) = (signum x, signum y) 569 | 570 | -- |'*$' provides scalar multiplication of a 2-tuple. 571 | -- 572 | -- >>> 2 *$ (1, 4) 573 | -- (2,8) 574 | -- 575 | (*$) :: Int -> (Int, Int) -> (Int, Int) 576 | n *$ (x, y) = (n * x, n * y) 577 | 578 | -- |The 'dir' function converts a cardinal direction (e.g. \'E') into a unit 579 | -- coordinate. 580 | -- 581 | -- >>> dir 'E' 582 | -- (1,0) 583 | -- 584 | dir 'E' = ( 1, 0) 585 | dir 'N' = ( 0, 1) 586 | dir 'W' = (-1, 0) 587 | dir 'S' = ( 0, -1) 588 | dir _ = ( 0, 0) 589 | 590 | -- |The 'rot' function rotates an (x, y) coordinate 90 degrees. 591 | -- 592 | -- >>> rot (-3, 4) 593 | -- (-4,-3) 594 | -- 595 | rot (x, y) = (-y, x) 596 | 597 | -- |The 'rotn' function rotates an (x, y) coordinate through n 90-degree 598 | -- turns. 599 | -- 600 | -- >>> rotn 2 (-3, 4) 601 | -- (3,-4) 602 | -- 603 | rotn 0 = id 604 | rotn n = rot . rotn ((n - 1) `mod` 4) 605 | 606 | -- |The 'manhattan' function provides a 2-tuple's Manhattan distance from the 607 | -- origin. 608 | -- 609 | -- >>> manhattan (-3, 4) 610 | -- 7 611 | -- 612 | manhattan (x, y) = abs x + abs y 613 | 614 | -- *** 3-D space 615 | 616 | -- |'Num' instance for 3-tuples 617 | instance (Num a, Num b, Num c) => Num (a, b, c) where 618 | (x, y, z) + (u, v, w) = (x + u, y + v, z + w) 619 | (x, y, z) * (u, v, w) = (x * u, y * v, z * w) 620 | negate (x, y, z) = (negate x, negate y, negate z) 621 | fromInteger x = (fromInteger x, 0, 0) 622 | abs (x, y, z) = (abs x, abs y, abs z) 623 | signum (x, y, z) = (signum x, signum y, signum z) 624 | 625 | t1 (x, _, _) = x 626 | t2 (_, x, _) = x 627 | t3 (_, _, x) = x 628 | 629 | -- *** 4-D space 630 | 631 | -- |'Num' instance for 4-tuples 632 | instance (Num a, Num b, Num c, Num d) => Num (a, b, c, d) where 633 | (w, x, y, z) + (h, i, j, k) = (w + h, x + i, y + j, z + k) 634 | (w, x, y, z) * (h, i, j, k) = (w * h, x * i, y * j, z * k) 635 | negate (w, x, y, z) = (negate w, negate x, negate y, negate z) 636 | fromInteger x = (fromInteger x, 0, 0, 0) 637 | abs (w, x, y, z) = (abs w, abs x, abs y, abs z) 638 | signum (w, x, y, z) = (signum w, signum x, signum y, signum z) 639 | 640 | s1 (x, _, _, _) = x 641 | s2 (_, x, _, _) = x 642 | s3 (_, _, x, _) = x 643 | s4 (_, _, _, x) = x 644 | 645 | -- |'Num' instance for 'Maybe' 'Num's 646 | instance Num a => Num (Maybe a) where 647 | x * y = (*) <$> x <*> y 648 | x + y = (+) <$> x <*> y 649 | abs = (abs <$>) 650 | signum = (signum <$>) 651 | fromInteger = (Just . fromInteger) 652 | negate = (negate <$>) 653 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | -------------------------------------------------------------------------------- /Makefile: -------------------------------------------------------------------------------- 1 | MAKEFLAGS += --silent 2 | FLAGS = -O2 3 | HFLAGS = $(FLAGS) -rtsopts -v0 -XNoImplicitPrelude -XTupleSections -XBangPatterns 4 | DONE1 = $(wildcard [1-9][ab].hs) 5 | DONE2 = $(wildcard [12][0-9][ab].hs) 6 | GHCCOMMAND = $(shell command -v ghc) 7 | DOCDIR = $(shell echo "$$(dirname $(GHCCOMMAND))/$$(dirname $$(readlink $(GHCCOMMAND)))/../share/doc") 8 | HADDOCK_FILES = $(wildcard $(DOCDIR)/*/html/libraries/*/*.haddock) 9 | HADDOCK_FLAGS = $(foreach file,$(HADDOCK_FILES),-i $(dir $(file)),$(file)) 10 | 11 | all: $(sort $(DONE1:%.hs=%.output)) $(sort $(DONE2:%.hs=%.output)) | doc/AOC.html 12 | @for output in $^; do /bin/echo -n "$${output/.output}: "; cat "$$output"; done 13 | 14 | installdeps: 15 | cabal install --lib vector split hashable parsec mtl extra 16 | cabal install --overwrite-policy=always doctest 17 | 18 | test: 19 | @make > /dev/null 20 | @make | grep -v 'ch:' > .output 21 | @diff -u .expected_output .output 22 | 23 | updatetest: 24 | @make > /dev/null 25 | @make | grep -v 'ch:' > .expected_output 26 | 27 | prof: prof.pdf 28 | 29 | %.pdf: %.latex 30 | @latex -output-format=pdf $< > /dev/null 31 | @rm -f *-eps-converted-to.pdf *.aux $<.log $<.dvi 32 | 33 | prof.latex: $(sort $(DONE1:%.hs=%.eps)) $(sort $(DONE2:%.hs=%.eps)) 34 | @echo "\\\\documentclass{article}\n\\\\usepackage[a4paper, margin=5mm]{geometry}\n\ 35 | \\\\usepackage{graphicx}\n\\\\begin{document}\n\ 36 | $(foreach file,$^,\n\\\\begin{figure}\n\\\\includegraphics[scale=1]{$(file:.eps=)}\n\\\\end{figure}\n)\ 37 | \n\\\\end{document}" > prof.latex 38 | 39 | %a.hp: %a %.input 40 | @./$< +RTS -hT -i0.001 < $*.input > /dev/null 41 | 42 | %b.hp: %b %.input 43 | @./$< +RTS -hT -i0.001 < $*.input > /dev/null 44 | 45 | %.eps: %.hp 46 | @hp2ps -c -e200mm $< 47 | @mv $*.ps $*.eps 48 | 49 | clean: 50 | @rm -f -- [0-9][0-9][ab] [0-9][ab] *.o *.hi *.so *.a *.hp *.eps *.aux *.latex *.log *.pdf 51 | 52 | distclean: clean 53 | @rm -rf -- *.output doc aoc.txt 54 | 55 | %a.output: %a %.input 56 | @./$< < $*.input > $@ 57 | 58 | %b.output: %b %.input 59 | @./$< < $*.input > $@ 60 | 61 | %:: %.hs 62 | @ghc $(HFLAGS) -o $@ $^ 63 | @rm -f -- $*.hi $*.o 64 | 65 | doc/AOC.html: AOC.hs 66 | @rm -rf doc AOC.txt 67 | @haddock -o doc --html --hyperlinked-source --use-unicode $(HADDOCK_FLAGS) $< > /dev/null 68 | @rm -f doc/doc-index*.html 69 | @haddock --hoogle --package-name aoc $< >& /dev/null 70 | @doctest AOC 71 | 72 | .PRECIOUS: % 73 | .PHONY: all clean distclean test updatetest prof 74 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Haskell Solutions to Advent of Code 2020 2 | 3 | Watch the [accompanying YouTube series](https://www.youtube.com/playlist?list=PLDRIsR-OaZkzN7iV6Q6MRmEVYL_HRz7GS) for full explanations of the code in this repo. 4 | -------------------------------------------------------------------------------- /get: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | cd "$(dirname "$0")" 4 | 5 | if [ -r .cookie ]; then 6 | . .cookie 7 | fi 8 | 9 | export TZ=EST 10 | thisyear="$(date +%Y)" 11 | thismonth="$(date +%m)" 12 | thisday="$(date +%d)" 13 | 14 | year=2020 15 | for day in {1..25}; do 16 | if [ "$thisyear" -ne "$year" -o "$thismonth" -ne 12 -o "$day" -gt "$thisday" ]; then 17 | exit 0 18 | fi 19 | filename="$day".input 20 | if [ -r "$filename" ]; then 21 | continue # make sure we don't fetch the same file twice! 22 | fi 23 | curl -sS -o "$filename" -b "$AOC_COOKIE" https://adventofcode.com/"$year"/day/"$day"/input 24 | done 25 | -------------------------------------------------------------------------------- /watcher: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | if ! command -v fswatch &> /dev/null; then 4 | echo "$0": Please install fswatch. >&2 5 | exit 1 6 | fi 7 | 8 | t="$(make 2>&1)" 9 | echo "$t" 10 | 11 | fswatch -o --event Updated --event Created -e ".*" -i ".*\\.hs$" . \ 12 | | xargs -I{} sh -c 't="$(make 2>&1)"; echo "$t"' 13 | --------------------------------------------------------------------------------