Skip to content

Commit

Permalink
Drastically improved the speed of day 5 part 2
Browse files Browse the repository at this point in the history
  • Loading branch information
tymscar committed Dec 5, 2024
1 parent 0ed333e commit 6e97c98
Show file tree
Hide file tree
Showing 2 changed files with 10 additions and 21 deletions.
1 change: 0 additions & 1 deletion 2024/kotlin/build.gradle.kts
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,6 @@ repositories {

dependencies {
testImplementation(kotlin("test"))
implementation("org.jetbrains.kotlinx:kotlinx-coroutines-core:1.6.4")
}

tasks.test {
Expand Down
30 changes: 10 additions & 20 deletions 2024/kotlin/src/main/kotlin/com/tymscar/day05/part2/part2.kt
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
package com.tymscar.day05.part2

import kotlinx.coroutines.*

private fun isValidUpdate(update: List<String>, orderingRules: Map<String, List<String>>): Boolean = update
.withIndex()
Expand All @@ -18,11 +17,11 @@ private fun correctUpdate(update: List<String>, orderingRules: Map<String, List<
correctedUpdate.withIndex().forEach { (index, page) ->
val previousPages = correctedUpdate.take(index)
val shouldBeLaterPages = orderingRules[page] ?: listOf()
if (previousPages.any { shouldBeLaterPages.contains(it) }) {
val firstPageToSwap = previousPages.first { shouldBeLaterPages.contains(it) }
val firstPageToSwapIndex = correctedUpdate.indexOf(firstPageToSwap)
correctedUpdate.removeAt(firstPageToSwapIndex)
correctedUpdate.add(index, firstPageToSwap)
val firstPageToSwapIndex = previousPages.indexOfFirst { shouldBeLaterPages.contains(it) }
if (firstPageToSwapIndex != -1) {
val firstPageToSwap = previousPages[firstPageToSwapIndex]
correctedUpdate[index] = firstPageToSwap
correctedUpdate[firstPageToSwapIndex] = page
return@breaking
}
}
Expand All @@ -42,18 +41,9 @@ fun solve(input: String): String {
.map { it.groupValues[0].split(",") }
.toList()

val invalidUpdates = pagesToCheck.filter { !isValidUpdate(it, orderingRules) }

return runBlocking {
val deferredResults = invalidUpdates.mapIndexed { index, update ->
async(Dispatchers.Default) {
val correctedUpdate = correctUpdate(update, orderingRules)
correctedUpdate[correctedUpdate.count() / 2].toInt()
}
}

val results = deferredResults.awaitAll()
return@runBlocking results.sum().toString()
}

return pagesToCheck
.filter { !isValidUpdate(it, orderingRules) }
.sumOf() { correctUpdate(it, orderingRules)
.let { it[it.count() / 2].toInt() } }
.toString()
}

0 comments on commit 6e97c98

Please sign in to comment.