diff --git a/README.md b/README.md index 08f234f..2a4d4a1 100644 --- a/README.md +++ b/README.md @@ -6,5 +6,5 @@ I started learning Haskell very recently, and I just learned this year that Adve |01 |★ ★ |06 |★ ★ |11 |★ ★ |16 |★ |21 | | |02 |★ ★ |07 |★ ★ |12 |★ |17 |★ ★ |22 |★ | |03 |★ ★ |08 |★ ★ |13 |★ ★ |18 |★ ★ |23 |★ | -|04 |★ ★ |09 |★ ★ |14 |★ ★ |19 |★ |24 | | +|04 |★ ★ |09 |★ ★ |14 |★ ★ |19 |★ |24 |★ | |05 |★ ★ |10 |★ ★ |15 |★ |20 | |25 | | diff --git a/adventofcode2024.cabal b/adventofcode2024.cabal index 808cf7c..093a979 100644 --- a/adventofcode2024.cabal +++ b/adventofcode2024.cabal @@ -59,4 +59,5 @@ executable adventofcode2024 Day19 Day22 Day23 + Day24 Graph diff --git a/src/Day24.hs b/src/Day24.hs new file mode 100644 index 0000000..a010eb1 --- /dev/null +++ b/src/Day24.hs @@ -0,0 +1,34 @@ +{-# OPTIONS_GHC -Wno-incomplete-uni-patterns #-} + +module Day24 (day24_1) where + +import Data.Bits +import qualified Data.HashMap.Strict as M +import Data.List (sort) +import Data.List.Split (splitOn) + +getWireValue :: String -> M.HashMap String (Maybe Int) -> M.HashMap String String -> Int +getWireValue w wm cm = + case wm M.! w of + Just x -> x + Nothing -> + let (w1 : op : w2 : _) = words $ cm M.! w + in if op == "AND" + then getWireValue w1 wm cm .&. getWireValue w2 wm cm + else + if op == "OR" + then getWireValue w1 wm cm .|. getWireValue w2 wm cm + else getWireValue w1 wm cm `xor` getWireValue w2 wm cm + +toDecimal :: [Int] -> Int +toDecimal n = sum $ zipWith (*) n (iterate (*2) 1) + +day24_1 :: IO () +day24_1 = do + [inputs, connections] <- splitOn [""] . lines <$> readFile "input/day24.txt" + let inputsList = [(i, Just ((read :: String -> Int) v)) | [i, v] <- map (splitOn ": ") inputs] + wireConnections = [(w, c) | [c, w] <- map (splitOn " -> ") connections] + connectionsMap = M.fromList wireConnections + wiresMap = M.fromList $ [(fst wc, Nothing) | wc <- wireConnections] ++ inputsList + outputs = map (\x -> getWireValue x wiresMap connectionsMap) (filter (\(x : _) -> x == 'z') . sort $ M.keys wiresMap) + print $ toDecimal outputs diff --git a/src/Main.hs b/src/Main.hs index 8a119bf..1641a3e 100644 --- a/src/Main.hs +++ b/src/Main.hs @@ -21,6 +21,7 @@ import Day18 (day18_1, day18_2) import Day19 (day19_1) import Day22 (day22_1) import Day23 (day23_1) +import Day24 (day24_1) import System.Environment (getArgs) main :: IO () @@ -108,6 +109,7 @@ main = do "19" : "1" : _ -> day19_1 "22" : "1" : _ -> day22_1 "23" : "1" : _ -> day23_1 + "24" : "1" : _ -> day24_1 "all" : _ -> do day01_1 day01_2 @@ -145,4 +147,5 @@ main = do day19_1 day22_1 day23_1 + day24_1 _ -> error "Not implemented"