Refresher on Coroutines for maximum parallel brute force for Day 22.

This commit is contained in:
Chris Hodges 2024-12-22 18:42:55 +01:00
parent bc542bd29c
commit 343414cd04

View File

@ -1,5 +1,9 @@
package aoc2024 package aoc2024
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.async
import kotlinx.coroutines.awaitAll
import kotlinx.coroutines.runBlocking
import println import println
import readInput import readInput
@ -50,7 +54,6 @@ fun main() {
val deltaString = StringBuffer(2024) val deltaString = StringBuffer(2024)
var v = i var v = i
var lastd = v % 10 var lastd = v % 10
normalString.append(lastd)
for (p in 1..2000) { for (p in 1..2000) {
v = next(v) v = next(v)
val d = v % 10 val d = v % 10
@ -64,26 +67,22 @@ fun main() {
} }
// it's not my fault that brute force is still working // it's not my fault that brute force is still working
val tokenBuffer = StringBuffer(5) return runBlocking {
tokenBuffer.append(" ") (0..(19 * 19 * 19 * 19)).map {
val maxIdx = deltaStrings[0].length - 3 async(Dispatchers.Default) {
var maxBananas = 0 val tokenBuffer = StringBuffer(4)
for (code in 0 until 19 * 19 * 19 * 19) { tokenBuffer.append('a' + (it / (19 * 19 * 19)))
tokenBuffer.setCharAt(0, 'a' + (code / (19 * 19 * 19))) tokenBuffer.append('a' + ((it / (19 * 19)) % 19))
tokenBuffer.setCharAt(1, 'a' + ((code / (19 * 19)) % 19)) tokenBuffer.append('a' + ((it / 19) % 19))
tokenBuffer.setCharAt(2, 'a' + ((code / 19) % 19)) tokenBuffer.append('a' + ((it % 19)))
tokenBuffer.setCharAt(3, 'a' + ((code % 19)))
var bananas = 0
val token = tokenBuffer.toString() val token = tokenBuffer.toString()
for (i in deltaStrings.indices) { deltaStrings.indices.sumOf {
val idx = deltaStrings[i].indexOf(token) val idx = deltaStrings[it].indexOf(token)
if (idx in 0..maxIdx) { if (idx >= 0) normalStrings[it][idx + 3].digitToInt() else 0
bananas += normalStrings[i][idx + 4].digitToInt()
} }
} }
maxBananas = maxBananas.coerceAtLeast(bananas) }.awaitAll().max()
} }
return maxBananas
} }
// test if implementation meets criteria from the description, like: // test if implementation meets criteria from the description, like: