From 45c4a2997c412b56d35b077fb500f75a3cab4468 Mon Sep 17 00:00:00 2001 From: Steve Dunham Date: Tue, 10 Dec 2024 22:04:27 -0800 Subject: [PATCH] day11 --- aoc2024/Day11.newt | 67 ++++++++++++++++++++++++++++++++++++++++++++ aoc2024/day11/eg.txt | 1 + 2 files changed, 68 insertions(+) create mode 100644 aoc2024/Day11.newt create mode 100644 aoc2024/day11/eg.txt diff --git a/aoc2024/Day11.newt b/aoc2024/Day11.newt new file mode 100644 index 0000000..eabff3f --- /dev/null +++ b/aoc2024/Day11.newt @@ -0,0 +1,67 @@ +module Day11 + +import Prelude +import Node +import Aoc +import SortedMap + +infixl 7 _%_ +pfunc _%_ : Int → Int → Int := `(x,y) => x % y` + +-- should have a few more foreign functions and do this in newt +pfunc divide uses (_,_) : String → String × String := `(s) => { + let l = s.length/2|0 + return _$2C_(undefined, undefined, s.slice(0,l), s.slice(l)) +}` + +step : List Int → List Int +step = go Nil + where + go : List Int → List Int → List Int + go acc Nil = acc + go acc (0 :: xs) = go (1 :: acc) xs + go acc (x :: xs) = + let str = show x in + if slen str % 2 == 0 + then let (a,b) = divide str in go (stringToInt a :: stringToInt b :: acc) xs + else go (2024 * x :: acc) xs + +foldMap : ∀ a b. {{Ord a}} {{Eq a}} → (b → b → b) → SortedMap a b → List (a × b) → SortedMap a b +foldMap f m Nil = m +foldMap f m ((a,b) :: xs) = case lookupMap a m of + Nothing => foldMap f (updateMap a b m) xs + Just (_, b') => foldMap f (updateMap a (f b' b) m) xs + +step2 : List (Int × Int) → List (Int × Int) +step2 = go Nil + where + go : List (Int × Int) → List (Int × Int) → List (Int × Int) + go acc Nil = acc + go acc ((0,c) :: xs) = go ((1,c) :: acc) xs + go acc ((x,c) :: xs) = + let str = show x in + if slen str % 2 == 0 + then let (a,b) = divide str in go ((stringToInt a,c) :: (stringToInt b,c) :: acc) xs + else go ((2024 * x,c) :: acc) xs + +iter : Int → SortedMap Int Int → Int +iter count parts = let x = go count parts in foldl _+_ 0 $ map snd $ toList x + where + go : Int → SortedMap Int Int → SortedMap Int Int + go 0 stuff = stuff + go x stuff = go (x - 1) $ foldMap _+_ EmptyMap $ step2 $ toList stuff + +run : String -> IO Unit +run fn = do + putStrLn fn + text <- readFile fn + let stuff = foldMap _+_ EmptyMap $ map (\ x => (stringToInt x, 1)) $ split (trim text) " " + let p1 = iter 25 stuff + putStrLn $ "part1 " ++ show p1 + let p2 = iter 75 stuff + putStrLn $ "iter " ++ show p2 + +main : IO Unit +main = do + run "aoc2024/day11/eg.txt" + run "aoc2024/day11/input.txt" diff --git a/aoc2024/day11/eg.txt b/aoc2024/day11/eg.txt new file mode 100644 index 0000000..9b26c84 --- /dev/null +++ b/aoc2024/day11/eg.txt @@ -0,0 +1 @@ +125 17