From 754daa65e4db1cde649448c9a2660535277b136b Mon Sep 17 00:00:00 2001 From: Matej Focko Date: Sat, 7 Dec 2024 18:24:17 +0100 Subject: [PATCH] =?UTF-8?q?day(07):=20use=20=E2=80=B9when=E2=80=BA=20expre?= =?UTF-8?q?ssion=20instead=20of=20body?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: Matej Focko --- src/Day07.kt | 27 ++++++++++++--------------- 1 file changed, 12 insertions(+), 15 deletions(-) diff --git a/src/Day07.kt b/src/Day07.kt index 5f017f3..1611dbc 100644 --- a/src/Day07.kt +++ b/src/Day07.kt @@ -7,22 +7,16 @@ private data class Equation( result: Long, i: Int, op: (Long, Long) -> Long, - ): Boolean { - // used all operands - if (i >= operands.size) { - return result == target + ): Boolean = + when { + i >= operands.size -> result == target + result > target -> false + else -> + ops.any { nextOp -> + canSatisfy(ops, op(result, operands[i]), i + 1, nextOp) + } } - // overshot - if (result > target) { - return false - } - - return ops.any { nextOp -> - canSatisfy(ops, op(result, operands[i]), i + 1, nextOp) - } - } - fun isSatisfiable(ops: List<(Long, Long) -> Long>): Boolean = canSatisfy(ops, 0L, 0, Long::plus) } @@ -65,7 +59,10 @@ class Day07( // no-op } - private fun getSum(ops: List<(Long, Long) -> Long>): Long = equations.filter { it.isSatisfiable(ops) }.sumOf { it.target } + private fun getSum(ops: List<(Long, Long) -> Long>): Long = + equations + .filter { it.isSatisfiable(ops) } + .sumOf { it.target } override fun part1(): Long = getSum(PART1_OPS)