Day 7 Part 2 optimized to 666ms (instead of around 3000ms).
This commit is contained in:
parent
ea9f44a12c
commit
8d492486fb
@ -4,7 +4,6 @@ import println
|
|||||||
import readInput
|
import readInput
|
||||||
import splitLongs
|
import splitLongs
|
||||||
import kotlin.math.pow
|
import kotlin.math.pow
|
||||||
import kotlin.math.roundToLong
|
|
||||||
|
|
||||||
/*
|
/*
|
||||||
--- Day 7: Bridge Repair ---
|
--- Day 7: Bridge Repair ---
|
||||||
@ -66,6 +65,16 @@ fun main() {
|
|||||||
return sum
|
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<String>): Long {
|
fun part2(input: List<String>): Long {
|
||||||
var sum = 0L
|
var sum = 0L
|
||||||
for (i in input) {
|
for (i in input) {
|
||||||
@ -75,10 +84,10 @@ fun main() {
|
|||||||
val combs = 3.0.pow(ops.size - 1).toInt()
|
val combs = 3.0.pow(ops.size - 1).toInt()
|
||||||
for (t in 0 until combs) {
|
for (t in 0 until combs) {
|
||||||
val res = ops.reduceIndexed { index, acc, l ->
|
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
|
0 -> acc + l
|
||||||
1 -> 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()
|
else -> throw IllegalArgumentException()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
Loading…
Reference in New Issue
Block a user