@@ -8,40 +8,31 @@ import java.util.*
8
8
import kotlin.math.*
9
9
import kotlin.system.exitProcess
10
10
11
- fun main () = solvePuzzle(year = 2024 , day = 7 , dryRun = false ) { Day7 (it) }
11
+ fun main () = solvePuzzle(year = 2024 , day = 7 , dryRun = true ) { Day7 (it) }
12
12
13
13
class Day7 (val input : Input ) : Puzzle {
14
14
15
- enum class Operator (val s : String , val op : (a: Long , b: Long ) -> Long ) {
16
- Add (" + " , { a, b -> a + b }),
17
- Multiply (" * " , { a, b -> a * b }),
18
- Concatenate (" || " , {a, b -> " $a$b " .toLong() }),
15
+ enum class Operator (val op : (a: Long , b: Long ) -> Long ) {
16
+ Add ({ a, b -> a + b }),
17
+ Multiply ({ a, b -> a * b }),
18
+ Concatenate ({a, b -> " $a$b " .toLong() }),
19
19
}
20
20
data class Equation (val testValue : Long , val numbers : List <Long >)
21
- data class Solution (val operators : List <Operator >)
22
21
23
- fun findSolutions (eq : Equation , availableOperators : List <Operator >, i : Int = 1, curTestValue : Long = eq.numbers[0], operators : MutableList < Operator > = mutableListOf()): List < Solution > {
22
+ fun hasSolutions (eq : Equation , availableOperators : List <Operator >, i : Int = 1, curTestValue : Long = eq.numbers[0]): Boolean {
24
23
if (curTestValue > eq.testValue) {
25
24
// No negative numbers, cannot reach testValue anymore.
26
- return emptyList()
25
+ return false
27
26
}
28
27
29
28
if (i == eq.numbers.size) {
30
- if (curTestValue == eq.testValue) {
31
- return listOf (Solution (operators.toList()))
32
- }
33
-
34
- return emptyList()
29
+ return curTestValue == eq.testValue
35
30
}
36
31
37
32
val num = eq.numbers[i]
38
- return availableOperators.flatMap { op ->
33
+ return availableOperators.any { op ->
39
34
val newTestValue = op.op(curTestValue, num)
40
-
41
- operators.add(op)
42
- val solutions = findSolutions(eq, availableOperators, i + 1 , newTestValue, operators)
43
- operators.removeLast()
44
- solutions
35
+ hasSolutions(eq, availableOperators, i + 1 , newTestValue)
45
36
}
46
37
}
47
38
@@ -56,15 +47,15 @@ class Day7(val input: Input) : Puzzle {
56
47
val equations = parseInput(input.lines)
57
48
58
49
return equations.filter { eq ->
59
- findSolutions (eq, listOf (Operator .Add , Operator .Multiply )).isNotEmpty( )
50
+ hasSolutions (eq, listOf (Operator .Add , Operator .Multiply ))
60
51
}.sumOf { it.testValue }
61
52
}
62
53
63
54
override fun solveLevel2 (): Any {
64
55
val equations = parseInput(input.lines)
65
56
66
57
return equations.filter { eq ->
67
- findSolutions (eq, listOf (Operator .Add , Operator .Multiply , Operator .Concatenate )).isNotEmpty( )
58
+ hasSolutions (eq, listOf (Operator .Add , Operator .Multiply , Operator .Concatenate ))
68
59
}.sumOf { it.testValue }
69
60
}
70
61
}
0 commit comments