Skip to content

Commit

Permalink
Calculating subgraph to O(V+E) complexity
Browse files Browse the repository at this point in the history
  • Loading branch information
jraska committed Jul 23, 2024
1 parent abc7391 commit 6dfe245
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 6 deletions.
16 changes: 12 additions & 4 deletions plugin/src/main/kotlin/com/jraska/module/graph/DependencyGraph.kt
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,7 @@ class DependencyGraph private constructor() {
require(nodes.contains(key)) { "Dependency Tree doesn't contain module: $key" }

val connections = mutableListOf<Pair<String, String>>()
addConnections(nodes.getValue(key), connections, mutableSetOf())
addConnections(nodes.getValue(key), connections, mutableSetOf(), mutableSetOf())

return if (connections.isEmpty()) {
createSingular(key)
Expand All @@ -79,9 +79,17 @@ class DependencyGraph private constructor() {
}

private fun addConnections(
node: Node, into: MutableList<Pair<String, String>>,
path: MutableSet<Node>
node: Node,
into: MutableList<Pair<String, String>>,
path: MutableSet<Node>,
visited: MutableSet<Node>,
) {
if (visited.contains(node)) {
return
} else {
visited.add(node)
}

path.add(node)
node.dependsOn.forEach { dependant ->
into.add(node.key to dependant.key)
Expand All @@ -91,7 +99,7 @@ class DependencyGraph private constructor() {
val pathText = path.joinToString(separator = ", ") { it.key }
throw IllegalStateException("Dependency cycle detected! Cycle in nodes: '${pathText}'.")
}
addConnections(dependant, into, path)
addConnections(dependant, into, path, visited)
}

path.remove(node)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -29,9 +29,27 @@ class DependencyGraphPerformanceTest {
assert(statistics.longestPath.pathString().startsWith("23 -> 31 -> 36 -> 57 -> 61 -> 72 -> 74 -> 75"))
}

@Test(timeout = 10000)
fun whenTheGraphIsLarge_statisticsSubGraphCreatedFast() {
@Test(timeout = 1_000)
fun whenTheGraphIsLarge_statisticsOfSubgraphMatchFast() {
val subGraphStatistics = dependencyGraph.subTree("31").statistics()

assert(subGraphStatistics.height == 58)
assert(subGraphStatistics.longestPath.pathString().startsWith("31 -> 36 -> 57 -> 61 -> 72 -> 74 -> 75"))
}

@Test(timeout = 1_000)
fun whenTheGraphIsLarge_statisticsCreatedFast() {
val subGraphStatistics = dependencyGraph.subTree("500").statistics()
assert(subGraphStatistics.modulesCount == 281)
}

@Test(timeout = 1_000) // was running out of heap before optimisation
fun whenTheGraphIsLarge_statisticsLargeCreatedFast() {
val subGraphStatistics = dependencyGraph.subTree("2").statistics()

assert(subGraphStatistics.modulesCount == 870)
assert(subGraphStatistics.edgesCount == 11650)
assert(subGraphStatistics.height == 55)
assert(subGraphStatistics.longestPath.pathString().startsWith("2 -> 30 -> 76 -> 105 -> 119 -> "))
}
}

0 comments on commit 6dfe245

Please sign in to comment.