@@ -5,13 +5,16 @@ import Aoc2024.Day07.Types
5
5
6
6
-- Part 1
7
7
8
+ private def concatenate (a : Int) (b : Int) : Int := (reprStr a ++ reprStr b).toInt!
9
+
8
10
private def evalNumbers (numbers : List Int) (operators : List Operator): Int :=
9
11
match numbers with
10
12
| [] => 0
11
13
| h :: t =>
12
14
t.zip operators |>.foldl (fun acc (n, op) => match op with
13
15
| .add => acc + n
14
16
| .multiply => acc * n
17
+ | .concatenation => concatenate acc n
15
18
) h
16
19
17
20
#guard evalNumbers [11 , 6 , 16 , 20 ] [.add, .multiply, .add] == 292
@@ -25,21 +28,22 @@ private def replicateM (n : Nat) (options : List α) : List (List α) :=
25
28
#guard replicateM 0 [1 , 2 ] == [[]]
26
29
#guard replicateM 3 [1 , 2 ] == [[1 , 1 , 1 ], [2 , 1 , 1 ], [1 , 2 , 1 ], [2 , 2 , 1 ], [1 , 1 , 2 ], [2 , 1 , 2 ], [1 , 2 , 2 ], [2 , 2 , 2 ]]
27
30
28
- private def canEquationPossiblyBeTrue (equation : Equation) : Bool :=
29
- let operators := replicateM equation.numbers.length [.add, .multiply]
31
+ private def canEquationPossiblyBeTrue (operators : List Operator) ( equation : Equation) : Bool :=
32
+ let operators := replicateM equation.numbers.length operators
30
33
operators.any λ ops => evalNumbers equation.numbers ops == equation.testValue
31
34
32
35
private def solvePart1 (equations : List Equation) : Int :=
33
- equations.filter canEquationPossiblyBeTrue |>.sumBy (λ e => e .testValue)
36
+ equations.filter ( canEquationPossiblyBeTrue [.add, .multiply]) |>.sumBy (· .testValue)
34
37
35
38
def parseAndSolvePart1 (s : String): Except String Int := parseEquations s |>.map solvePart1
36
39
37
40
#guard parseAndSolvePart1 exampleInput == Except.ok 3749
38
41
39
42
-- Part 2
40
43
41
- private def solvePart2 (equations : List Equation) : Int := sorry
44
+ private def solvePart2 (equations : List Equation) : Int :=
45
+ equations.filter (canEquationPossiblyBeTrue [.add, .multiply, .concatenation]) |>.sumBy (·.testValue)
42
46
43
47
def parseAndSolvePart2 (s : String): Except String Int := parseEquations s |>.map solvePart2
44
48
45
- -- #guard parseAndSolvePart2 exampleInput == Except.ok -1
49
+ #guard parseAndSolvePart2 exampleInput == Except.ok 11387
0 commit comments