From 36c97f0d327d359e5a674828c88cb0f2fa70cc4a Mon Sep 17 00:00:00 2001 From: Daniel Lin Date: Thu, 5 Dec 2024 09:22:28 -0500 Subject: [PATCH] Use Map for a bit of speed-up --- .../com/github/ephemient/aoc2024/Day5.kt | 22 ++++++++++--------- 1 file changed, 12 insertions(+), 10 deletions(-) diff --git a/kt/aoc2024-lib/src/commonMain/kotlin/com/github/ephemient/aoc2024/Day5.kt b/kt/aoc2024-lib/src/commonMain/kotlin/com/github/ephemient/aoc2024/Day5.kt index 2c27e221..ef8e6340 100644 --- a/kt/aoc2024-lib/src/commonMain/kotlin/com/github/ephemient/aoc2024/Day5.kt +++ b/kt/aoc2024-lib/src/commonMain/kotlin/com/github/ephemient/aoc2024/Day5.kt @@ -1,15 +1,17 @@ package com.github.ephemient.aoc2024 class Day5(input: String) { - private val deps: Set + private val rdeps: Map> private val updates: List> init { val (deps, updates) = input.split("\n\n") - this.deps = deps.lines().mapTo(mutableSetOf()) { line -> - val (first, second) = line.split('|', limit = 2) - first.toInt() to second.toInt() - } + this.rdeps = deps.lineSequence() + .groupingBy { it.substringAfter('|').toInt() } + .aggregate { _, accumulator: MutableSet?, element, _ -> + val value = element.substringBefore('|').toInt() + accumulator?.apply { add(value) } ?: mutableSetOf(value) + } this.updates = updates.lines().mapNotNull { line -> line.ifEmpty { return@mapNotNull null }.split(',').map { it.toInt() } } @@ -18,7 +20,7 @@ class Day5(input: String) { fun part1() = updates.sumOf { pages -> if ( pages.withIndex().all { (i, x) -> - pages.subList(i + 1, pages.size).all { y -> y to x !in deps } + rdeps[x]?.let { pages.subList(i + 1, pages.size).any(it::contains) } != true } ) pages[pages.size / 2] else 0 } @@ -28,10 +30,10 @@ class Day5(input: String) { for (i in pages.indices) { while (true) { val x = pages[i] - val j = i + 1 + pages.subList(i + 1, pages.size).indexOfFirst { it to x in deps } - if (j > i) { - pages[i] = pages[j] - pages[j] = x + val j = pages.subList(i + 1, pages.size).indexOfFirst(rdeps[x].orEmpty()::contains) + if (j >= 0) { + pages[i] = pages[i + 1 + j] + pages[i + 1 + j] = x } else break } }