Skip to content

Commit e02947c

Browse files
committed
Day 7: optimize
1 parent cbf46af commit e02947c

File tree

1 file changed

+12
-21
lines changed

1 file changed

+12
-21
lines changed

src/main/kotlin/y24/Day7.kt

+12-21
Original file line numberDiff line numberDiff line change
@@ -8,40 +8,31 @@ import java.util.*
88
import kotlin.math.*
99
import kotlin.system.exitProcess
1010

11-
fun main() = solvePuzzle(year = 2024, day = 7, dryRun = false) { Day7(it) }
11+
fun main() = solvePuzzle(year = 2024, day = 7, dryRun = true) { Day7(it) }
1212

1313
class Day7(val input: Input) : Puzzle {
1414

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() }),
1919
}
2020
data class Equation(val testValue: Long, val numbers: List<Long>)
21-
data class Solution(val operators: List<Operator>)
2221

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 {
2423
if (curTestValue > eq.testValue) {
2524
// No negative numbers, cannot reach testValue anymore.
26-
return emptyList()
25+
return false
2726
}
2827

2928
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
3530
}
3631

3732
val num = eq.numbers[i]
38-
return availableOperators.flatMap { op ->
33+
return availableOperators.any { op ->
3934
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)
4536
}
4637
}
4738

@@ -56,15 +47,15 @@ class Day7(val input: Input) : Puzzle {
5647
val equations = parseInput(input.lines)
5748

5849
return equations.filter { eq ->
59-
findSolutions(eq, listOf(Operator.Add, Operator.Multiply)).isNotEmpty()
50+
hasSolutions(eq, listOf(Operator.Add, Operator.Multiply))
6051
}.sumOf { it.testValue }
6152
}
6253

6354
override fun solveLevel2(): Any {
6455
val equations = parseInput(input.lines)
6556

6657
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))
6859
}.sumOf { it.testValue }
6960
}
7061
}

0 commit comments

Comments
 (0)