
commonMain.com.toxicbakery.kfinstatemachine.graph.mapPaths.kt Maven / Gradle / Ivy
package com.toxicbakery.kfinstatemachine.graph
/**
* Map all unique acyclic paths from a given starting point.
*
* @param start the node to begin the search for unique paths through the graph
*/
fun IDirectedGraph.mapAcyclicPaths(
start: N
): Set> = mapAcyclicPaths(mutableListOf(start))
private fun IDirectedGraph.mapAcyclicPaths(
currentPath: MutableList,
pathSet: MutableSet> = mutableSetOf()
): Set> = edges(currentPath.last()) { mapOf() }
.also { edges ->
if (edges.isNotEmpty()) {
edges.forEach { edge ->
if (currentPath.contains(edge.value)) {
// Avoid loops and end the path
pathSet.add(currentPath)
} else {
// Copy the path and start a recursive search
currentPath.plus(edge.value)
.toMutableList()
.let { currentPath ->
mapAcyclicPaths(currentPath = currentPath, pathSet = pathSet)
}
}
}
} else pathSet.add(currentPath)
}
.let { pathSet }
© 2015 - 2025 Weber Informatics LLC | Privacy Policy