From 8d492486fb2aedf75a599c45eebc513635135b9d Mon Sep 17 00:00:00 2001 From: chrisly42 Date: Sat, 7 Dec 2024 07:13:32 +0100 Subject: [PATCH] Day 7 Part 2 optimized to 666ms (instead of around 3000ms). --- src/aoc2024/Day07.kt | 15 ++++++++++++--- 1 file changed, 12 insertions(+), 3 deletions(-) diff --git a/src/aoc2024/Day07.kt b/src/aoc2024/Day07.kt index 8680eda..4ff38d8 100644 --- a/src/aoc2024/Day07.kt +++ b/src/aoc2024/Day07.kt @@ -4,7 +4,6 @@ import println import readInput import splitLongs import kotlin.math.pow -import kotlin.math.roundToLong /* --- Day 7: Bridge Repair --- @@ -66,6 +65,16 @@ fun main() { return sum } + val powTenTable = generateSequence(1L) { it * 10L }.take(10).toList().toLongArray() + val powThreeTable = generateSequence(1) { it * 3 }.take(12).toList().toIntArray() + + fun fastCeilLog10(n: Long): Int { + for (i in 1 until 9) { + if (powTenTable[i] > n) return i + } + return -1 + } + fun part2(input: List): Long { var sum = 0L for (i in input) { @@ -75,10 +84,10 @@ fun main() { val combs = 3.0.pow(ops.size - 1).toInt() for (t in 0 until combs) { val res = ops.reduceIndexed { index, acc, l -> - when ((t / (3.0.pow(index - 1).toInt())) % 3) { + when ((t / powThreeTable[index - 1]) % 3) { 0 -> acc + l 1 -> acc * l - 2 -> acc * (10.0.pow(l.toString().length.toDouble()).roundToLong()) + l + 2 -> acc * powTenTable[fastCeilLog10(l)] + l else -> throw IllegalArgumentException() } }