You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

42 lines
1.3 KiB
Kotlin

package me.eater.hefbrug.executor
import me.eater.hefbrug.definition.AbstractDefinition
import me.eater.hefbrug.definition.DefinitionKey
import me.eater.hefbrug.definition.DefinitionSkeleton
object GraphBuilder {
fun makeGraph(input: Map<DefinitionKey, DefinitionSkeleton<*, *>>): List<Set<DefinitionKey>> {
val dependencies = mutableMapOf<DefinitionKey, MutableSet<DefinitionKey>>()
for ((key, definition) in input) {
definition.before.forEach {
dependencies.getOrPut(it, ::mutableSetOf)
.add(key)
}
definition.after.forEach {
dependencies.getOrPut(key, ::mutableSetOf)
.add(it)
}
}
val todo = input.keys.toMutableSet()
val fulfilled = mutableSetOf<DefinitionKey>()
val graphLayers = mutableListOf<Set<DefinitionKey>>()
while (todo.isNotEmpty()) {
val nextLayer = mutableSetOf<DefinitionKey>()
for (item in todo) {
if (dependencies[item]?.all { it in fulfilled } != false) {
nextLayer.add(item)
}
}
fulfilled += nextLayer
todo -= nextLayer
graphLayers.add(nextLayer)
}
return graphLayers
}
}