From fd05f1a7f2f3841733abf205bb48755160b3a51b Mon Sep 17 00:00:00 2001 From: Matej Focko Date: Sat, 7 Dec 2024 18:15:49 +0100 Subject: [PATCH] day(07): solve Signed-off-by: Matej Focko --- inputs/day07/sample.txt | 9 +++++ src/Day07.kt | 76 +++++++++++++++++++++++++++++++++++++++++ 2 files changed, 85 insertions(+) create mode 100644 inputs/day07/sample.txt create mode 100644 src/Day07.kt diff --git a/inputs/day07/sample.txt b/inputs/day07/sample.txt new file mode 100644 index 0000000..87b8b25 --- /dev/null +++ b/inputs/day07/sample.txt @@ -0,0 +1,9 @@ +190: 10 19 +3267: 81 40 27 +83: 17 5 +156: 15 6 +7290: 6 8 6 15 +161011: 16 10 13 +192: 17 8 14 +21037: 9 7 18 13 +292: 11 6 16 20 \ No newline at end of file diff --git a/src/Day07.kt b/src/Day07.kt new file mode 100644 index 0000000..0124747 --- /dev/null +++ b/src/Day07.kt @@ -0,0 +1,76 @@ +private data class Equation( + val target: Long, + val operands: List, +) { + private fun canSatisfy( + ops: List<(Long, Long) -> Long>, + result: Long, + i: Int, + op: (Long, Long) -> Long, + ): Boolean { + // used all operands + if (i >= operands.size) { + return result == target + } + + // 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) + + val satisfiable: Boolean + get() = canSatisfy(listOf(Long::plus, Long::times), 0L, 0, Long::plus) +} + +private fun String.toEquation(): Equation = + split(": ").let { (target, operands) -> + Equation(target.toLong(), operands.split(" ").map { it.toLong() }) + } + +class Day07( + inputType: String, +) : Day() { + private val equations: List = readInput(7, inputType).map { it.toEquation() }.toList() + + companion object { + fun concat( + x: Long, + y: Long, + ): Long { + val shift = + let { + var result = 1 + + var yy = y + while (yy > 0) { + yy /= 10 + result *= 10 + } + + return@let result + } + + return x * shift + y + } + } + + override fun precompute() { + // no-op + } + + override fun part1(): Long = equations.filter { it.satisfiable }.sumOf { it.target } + + override fun part2(): Long = equations.filter { it.isSatisfiable(listOf(Long::plus, Long::times, ::concat)) }.sumOf { it.target } +} + +fun main() { + Day07("sample").test(3749L, 11387L) + Day07("input").run() +}