From 9f3a4cad5e39f68bb548abd7f9a0f5993af9a360 Mon Sep 17 00:00:00 2001 From: Daniel Lin Date: Fri, 6 Dec 2024 02:36:57 -0500 Subject: [PATCH] Reuse data between part 1 and 2 --- .../com/github/ephemient/aoc2024/Day6.kt | 21 +++++++++---------- 1 file changed, 10 insertions(+), 11 deletions(-) diff --git a/kt/aoc2024-lib/src/commonMain/kotlin/com/github/ephemient/aoc2024/Day6.kt b/kt/aoc2024-lib/src/commonMain/kotlin/com/github/ephemient/aoc2024/Day6.kt index e210055..ca953e6 100644 --- a/kt/aoc2024-lib/src/commonMain/kotlin/com/github/ephemient/aoc2024/Day6.kt +++ b/kt/aoc2024-lib/src/commonMain/kotlin/com/github/ephemient/aoc2024/Day6.kt @@ -3,6 +3,7 @@ package com.github.ephemient.aoc2024 import kotlinx.coroutines.ExperimentalCoroutinesApi import kotlinx.coroutines.flow.asFlow import kotlinx.coroutines.flow.count +import kotlinx.coroutines.flow.drop import kotlinx.coroutines.flow.filter import kotlinx.coroutines.flow.flatMapMerge import kotlinx.coroutines.flow.flowOf @@ -13,20 +14,18 @@ class Day6(input: String) { val x = line.indexOf('^') if (x >= 0) y to x else null } + private val initialWalk: Set by lazy(LazyThreadSafetyMode.PUBLICATION) { + lines.walk(initialPosition).mapTo(mutableSetOf()) { it.first } + } - fun part1() = lines.walk(initialPosition).mapTo(mutableSetOf()) { it.first }.size + fun part1() = initialWalk.size @OptIn(ExperimentalCoroutinesApi::class) - suspend fun part2() = lines.walk(initialPosition) - .mapTo(mutableSetOf()) { it.first } - .apply { remove(initialPosition) } - .asFlow() - .flatMapMerge { (y, x) -> - val lines = lines.toMutableList() - lines[y] = StringBuilder(lines[y]).apply { set(x, '#') }.toString() - flowOf(Unit).filter { !lines.walk(initialPosition).all(mutableSetOf()::add) } - } - .count() + suspend fun part2() = initialWalk.asFlow().drop(1).flatMapMerge { (y, x) -> + val lines = lines.toMutableList() + lines[y] = StringBuilder(lines[y]).apply { set(x, '#') }.toString() + flowOf(Unit).filter { !lines.walk(initialPosition).all(mutableSetOf()::add) } + }.count() companion object { private fun List.walk(position: IntPair) = sequence {