Day 11, Part 2 + improved Part 1

This commit is contained in:
daniele 2024-12-12 09:34:37 +01:00
parent 720f1f8559
commit ebfa5b0f6b
Signed by: fuxino
GPG Key ID: 981A2B2A3BBF5514
2 changed files with 31 additions and 12 deletions

View File

@ -1,15 +1,17 @@
blinkStone :: Int -> [Int]
blinkStone 0 = [1]
blinkStone s = let ss = show s
nDigit = length ss
in if even nDigit
then map read [take (nDigit `div` 2) ss, drop (nDigit `div` 2) ss]
else [s * 2024]
import qualified Data.Map.Strict as M
blink :: Int -> [Int] -> [Int]
blink 0 xs = xs
blink n xs = blink (n - 1) $ concatMap blinkStone xs
blinkStone :: (Int, Int) -> [(Int, Int)]
blinkStone (0, n) = [(1, n)]
blinkStone (s, n) = let ss = show s
nDigit = length ss
in if even nDigit
then zip (map read [take (nDigit `div` 2) ss, drop (nDigit `div` 2) ss]) [n, n]
else [(s * 2024, n)]
blink :: Int -> M.Map Int Int -> M.Map Int Int
blink 0 m = m
blink n m = blink (n - 1) $ M.fromListWith (+) $ concatMap blinkStone $ M.toList m
main = do
contents <- words <$> readFile "day11.txt"
print . length . blink 25 $ map read contents
contents <- M.fromListWith (+) . flip zip (repeat 1) . map read . words <$> readFile "day11.txt"
print . M.foldl (+) 0 $ blink 25 contents

17
Day11/puzzle2.hs Normal file
View File

@ -0,0 +1,17 @@
import qualified Data.Map.Strict as M
blinkStone :: (Int, Int) -> [(Int, Int)]
blinkStone (0, n) = [(1, n)]
blinkStone (s, n) = let ss = show s
nDigit = length ss
in if even nDigit
then zip (map read [take (nDigit `div` 2) ss, drop (nDigit `div` 2) ss]) [n, n]
else [(s * 2024, n)]
blink :: Int -> M.Map Int Int -> M.Map Int Int
blink 0 m = m
blink n m = blink (n - 1) $ M.fromListWith (+) $ concatMap blinkStone $ M.toList m
main = do
contents <- M.fromListWith (+) . flip zip (repeat 1) . map read . words <$> readFile "day11.txt"
print . M.foldl (+) 0 $ blink 75 contents