day(05): fix linting and convert state to enum

Signed-off-by: Matej Focko <me@mfocko.xyz>
This commit is contained in:
Matej Focko 2024-12-05 15:12:31 +01:00
parent ab88740e69
commit 73fd14df89
Signed by: mfocko
SSH key fingerprint: SHA256:icm0fIOSJUpy5+1x23sfr+hLtF9UhY8VpMC7H4WFJP8

View file

@ -4,10 +4,10 @@ class Day05(
private val rules: Map<Int, MutableSet<Int>> private val rules: Map<Int, MutableSet<Int>>
private val updates: List<List<Int>> private val updates: List<List<Int>>
companion object { private enum class VertexState {
val UNVISITED = 0 Unvisited,
val OPEN = 1 Open,
val DONE = 2 Done,
} }
init { init {
@ -29,7 +29,7 @@ class Day05(
private fun printGraph() { private fun printGraph() {
println("digraph G {") println("digraph G {")
rules.forEach { u, vs -> rules.forEach { (u, vs) ->
vs.forEach { v -> vs.forEach { v ->
println("\t$u -> $v") println("\t$u -> $v")
} }
@ -54,19 +54,19 @@ class Day05(
// Toposort // Toposort
private fun fix(xs: Set<Int>): List<Int> { private fun fix(xs: Set<Int>): List<Int> {
val ordering = mutableListOf<Int>() val ordering = mutableListOf<Int>()
val state = mutableMapOf<Int, Int>() val state = mutableMapOf<Int, VertexState>()
fun visit(u: Int) { fun visit(u: Int) {
if (state.getOrDefault(u, UNVISITED) == DONE) { if (state.getOrDefault(u, VertexState.Unvisited) == VertexState.Done) {
return return
} }
check(state.getOrDefault(u, UNVISITED) != OPEN) { "We have found a loop ending in $u" } check(state.getOrDefault(u, VertexState.Unvisited) != VertexState.Open) { "We have found a loop ending in $u" }
state[u] = OPEN state[u] = VertexState.Open
// .intersect(): Recursively search only the interesting successors // .intersect(): Recursively search only the interesting successors
rules.getOrDefault(u, emptySet()).intersect(xs).forEach { visit(it) } rules.getOrDefault(u, emptySet()).intersect(xs).forEach { visit(it) }
state[u] = DONE state[u] = VertexState.Done
ordering.add(u) ordering.add(u)
} }
xs.forEach { visit(it) } xs.forEach { visit(it) }