Skip to content

Commit

Permalink
Further speed up with an early exit when the first element is bigger …
Browse files Browse the repository at this point in the history
…than the solution.
  • Loading branch information
PaulWoitaschek committed Dec 7, 2024
1 parent 475d96c commit c3ad087
Showing 1 changed file with 11 additions and 6 deletions.
17 changes: 11 additions & 6 deletions 2024/src/main/kotlin/aoc/year2024/Day7.kt
Original file line number Diff line number Diff line change
Expand Up @@ -28,17 +28,22 @@ object Day7 : Puzzle<Long, Long>(day = 7) {
private fun isSolvable(
solution: Long,
operators: List<Operator>,
input: List<Long>,
elements: List<Long>,
): Boolean {
if (input.size == 1) {
return input.first() == solution
if (elements.size == 1) {
return elements.first() == solution
}

// performance optimization
if (elements.first() > solution) {
return false
}

return operators.any { operator ->
isSolvable(
solution,
operators,
input.toMutableList().apply {
solution = solution,
operators = operators,
elements = elements.toMutableList().apply {
val first = removeAt(0)
val second = removeAt(0)
val value = when (operator) {
Expand Down

0 comments on commit c3ad087

Please sign in to comment.