|
1 | 1 | import Aoc2024.Utils
|
2 | 2 | import Aoc2024.Day05.Examples
|
3 | 3 | import Aoc2024.Day05.Parser
|
| 4 | +open Std (HashSet) |
4 | 5 |
|
5 |
| -private def solvePart1 (things : List Int) : Int := sorry |
| 6 | +-- Part 1 |
6 | 7 |
|
7 |
| -def parseAndSolvePart1 (s : String): Except String Int := parseThings s |>.map solvePart1 |
| 8 | +private def middleElement {α} (l : List α) : Option α := l.get? (l.length / 2) |
8 | 9 |
|
9 |
| --- #guard parseAndSolvePart1 exampleInput == Except.ok 2 |
| 10 | +private def middlePageNumber (update : Update) : Int := middleElement update.pages |>.getD 0 |
10 | 11 |
|
11 |
| -private def solvePart2 (things : List Int) : Int := sorry |
| 12 | +private def isCorrectlyOrdered (rules : List OrderingRule) (update : Update) : Bool := |
| 13 | + let allowedPairs := rules.map (·.toPair) |>.toSet |
| 14 | + update.pages.slidingPairs.toSet.isSubsetOf allowedPairs |
12 | 15 |
|
13 |
| -def parseAndSolvePart2 (s : String): Except String Int := parseThings s |>.map solvePart2 |
| 16 | +private def solvePart1 (input : PuzzleInput) : Int := |
| 17 | + input.updates.filter (isCorrectlyOrdered input.rules) |
| 18 | + |>.sumBy middlePageNumber |
14 | 19 |
|
15 |
| --- #guard parseAndSolvePart2 exampleInput == Except.ok 4 |
| 20 | +def parseAndSolvePart1 (s : String): Except String Int := parseInput s |>.map solvePart1 |
| 21 | + |
| 22 | +#guard parseAndSolvePart1 exampleInput == Except.ok 143 |
| 23 | + |
| 24 | +-- Part 2 |
| 25 | + |
| 26 | +private def orderCorrectly (rules : List OrderingRule) (update : Update) : Update := |
| 27 | + let allowedPairs := rules.map (·.toPair) |>.toSet |
| 28 | + let reorderedPages := update.pages.mergeSort (λ p1 p2 => p1 == p2 || allowedPairs.contains (p1, p2)) |
| 29 | + { pages := reorderedPages } |
| 30 | + |
| 31 | +private def solvePart2 (input : PuzzleInput) : Int := |
| 32 | + input.updates.filterNot (isCorrectlyOrdered input.rules) |
| 33 | + |>.map (orderCorrectly input.rules) |
| 34 | + |>.sumBy middlePageNumber |
| 35 | + |
| 36 | +def parseAndSolvePart2 (s : String): Except String Int := parseInput s |>.map solvePart2 |
| 37 | + |
| 38 | +#guard parseAndSolvePart2 exampleInput == Except.ok 123 |
0 commit comments