All Downloads are FREE. Search and download functionalities are using the official Maven repository.

commonMain.com.toxicbakery.kfinstatemachine.graph.mapPaths.kt Maven / Gradle / Ivy

The newest version!
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))
        .minus>(listOf(start))

/**
 * Recursively walk unique acyclic paths from a given path and map of known paths.
 *
 * @param currentPath path to be walked
 * @param pathSet paths previously walked
 */
private fun  IDirectedGraph.mapAcyclicPaths(
        currentPath: List,
        pathSet: MutableSet> = mutableSetOf()
): Set> = edges(currentPath.last()) { mapOf() }
        .let { edges ->
            if (edges.isNotEmpty()) {
                edges.forEach { edge ->
                    when {
                        // Avoid loops and end the path
                        currentPath.contains(edge.value) -> pathSet.add(currentPath)
                        // Copy the path and start a recursive search
                        else -> mapAcyclicPaths(
                                currentPath = currentPath.plus(edge.value),
                                pathSet = pathSet
                        )
                    }
                }
            } else pathSet.add(currentPath)
            return pathSet
        }




© 2015 - 2025 Weber Informatics LLC | Privacy Policy