From e33af7d7b2c0cf6d0f9d7b046a6717a6aa80a369 Mon Sep 17 00:00:00 2001 From: Ville Penttinen Date: Thu, 5 Dec 2024 08:45:20 +0200 Subject: [PATCH] feat(aoc2024): day5 part2 --- visp/examples/aoc2024/day5.visp | 53 ++++++++++++++++++++------------- 1 file changed, 33 insertions(+), 20 deletions(-) diff --git a/visp/examples/aoc2024/day5.visp b/visp/examples/aoc2024/day5.visp index 9e1d154..588d0ab 100644 --- a/visp/examples/aoc2024/day5.visp +++ b/visp/examples/aoc2024/day5.visp @@ -74,7 +74,6 @@ ) (fn rec Rules_IsBeforeAllOf [(before: int32) (rest: PageUpdate) (rules: Rules)] - (match (Map.tryFind before rules) [(Some afters) ;; @@ -90,9 +89,7 @@ (List.forall #( not (Rules_IsBeforeAllOf %1 (| before |) rules) ))) - ] - ) - ) + ])) (fn UpdateInCorrectOrder [(upd: PageUpdate) (rules: Rules)] (fn rec loop ([up: PageUpdate] [rules: Rules] (correct: bool)) @@ -100,21 +97,9 @@ [(not correct) correct] [_ (match up - [(cur :: rest) - ;; todo - ;; (printfn "checking %A and %A" cur rest) - - (loop rest rules (Rules_IsBeforeAllOf cur rest rules)) - ] + [(cur :: rest) (loop rest rules (Rules_IsBeforeAllOf cur rest rules)) ] [[] correct] - ) ])) - ;; (->> upd - ;; (List.pairwise) - ;; (List.forall #(begin - ;; (let (lhs, rhs) %1) - - ;; false - ;; ))) + )])) (loop upd rules true)) (fn Update_PickMiddle [(upd: PageUpdate)] @@ -122,6 +107,30 @@ ;; (printfn "valid %A %A" upd len) (List.item len upd)) +(fn Update_Fix [(rules: Rules) (upd: PageUpdate)] + ;; (printfn "valid %A %A" upd len) + (fn rec loop ([up: PageUpdate] [rules: Rules] [fixed: PageUpdate]) + (match up + [[] (List.rev fixed)] + [(cur :: []) + (-> (cons cur fixed) (List.rev)) + ] + [(cur :: next :: rest) + (cond_ + [(Rules_IsBeforeAllOf cur (cons next rest) rules) + (loop (cons next rest) rules (cons cur fixed)) + ] + [(Rules_IsBeforeAllOf next (cons cur rest) rules) + (loop (cons cur rest) rules (cons next fixed)) + ] + [_ (loop (List.concat (| rest (| cur next |)|)) rules fixed)] + ) + ] + ) + ) + + (loop upd rules (||))) + (fn Part1 (parsedInput) ;; (printfn "%A" parsedInput) ;; Implement part1 @@ -132,7 +141,11 @@ (fn Part2 (parsedInput) ;; Implement part2 - 0) + (->> (+updates parsedInput) + (List.filter #(not (UpdateInCorrectOrder %1 (+rules parsedInput)))) + (List.map (Update_Fix (+rules parsedInput))) + (List.map Update_PickMiddle) + (List.sum))) ;; Implementation @@ -140,7 +153,7 @@ ;; Expected results (let PART1_EXPECTED_RESULT (if IS_EXAMPLE 143 4637)) -(let PART2_EXPECTED_RESULT (if IS_EXAMPLE -1 -1)) +(let PART2_EXPECTED_RESULT (if IS_EXAMPLE 123 6370)) (WriteResult "part1" (-> parsed Part1) PART1_EXPECTED_RESULT) (WriteResult "part2" (-> parsed Part2) PART2_EXPECTED_RESULT)