From 1425c6c51d7cb5b6906aa0061f9c191b4322825a Mon Sep 17 00:00:00 2001 From: Kiana Sheibani Date: Mon, 2 Dec 2024 17:05:34 -0500 Subject: [PATCH] feat: part 1-2 --- advent-of-code-2024.ipkg | 3 +-- src/AllDays.idr | 1 + src/Day1/Part1.idr | 1 + src/Day1/Part2.idr | 31 +++++++++++++++++++++++++++++++ src/Main.idr | 3 +-- 5 files changed, 35 insertions(+), 4 deletions(-) create mode 100644 src/Day1/Part2.idr diff --git a/advent-of-code-2024.ipkg b/advent-of-code-2024.ipkg index 37257e6..03eb6b3 100644 --- a/advent-of-code-2024.ipkg +++ b/advent-of-code-2024.ipkg @@ -14,5 +14,4 @@ executable = advent-of-code-2024 main = Main modules = Main, Utils, AllDays, Data.Problem, - Day1.Part1 - + Day1.Part1, Day1.Part2 diff --git a/src/AllDays.idr b/src/AllDays.idr index 01e67ea..c384c4b 100644 --- a/src/AllDays.idr +++ b/src/AllDays.idr @@ -1,3 +1,4 @@ module AllDays import public Day1.Part1 +import public Day1.Part2 diff --git a/src/Day1/Part1.idr b/src/Day1/Part1.idr index b10eb4f..1116820 100644 --- a/src/Day1/Part1.idr +++ b/src/Day1/Part1.idr @@ -16,6 +16,7 @@ parseLine str = | _ => Nothing in (,) <$> parseNat n1 <*> parseNat n2 +export parseInput : String -> Maybe (List Nat, List Nat) parseInput = map unzip . traverse parseLine . lines diff --git a/src/Day1/Part2.idr b/src/Day1/Part2.idr new file mode 100644 index 0000000..083d0d7 --- /dev/null +++ b/src/Day1/Part2.idr @@ -0,0 +1,31 @@ +module Day1.Part2 + +import Data.Maybe +import Data.SortedMap + +import Day1.Part1 + +%default total + +--- DATA + +process : (left, right : List Nat) -> Nat +process = go Z empty + where + go : (out : Nat) -> (cache : SortedMap Nat Nat) + -> (left, right : List Nat) -> Nat + go out _ [] _ = out + go out cache (n :: left) right = + let cached = lookup n cache + score = case cached of + Just c => c + Nothing => n * count (==n) right + in go (score + out) (if isJust cached + then cache + else insert n score cache) left right + +--- SOLUTION + +export +solution : String -> Maybe Nat +solution = map (uncurry process) . parseInput diff --git a/src/Main.idr b/src/Main.idr index 9cc0eb4..9cb5f9c 100644 --- a/src/Main.idr +++ b/src/Main.idr @@ -1,7 +1,6 @@ module Main import Data.List1 -import Data.Maybe import Data.String import Data.SortedMap import Data.SortedMap.Dependent @@ -17,7 +16,7 @@ import AllDays ||| The latest problem that has been solved. -- NOTE: UPDATE AFTER EACH SOLUTION latest : Problem -latest = Pr 1 Part1 +latest = Pr 1 Part2 solMap : SortedMap Problem (String -> String)