Skip to content

Commit

Permalink
feat(graph-support): bump Guava and add new APIs to Graphs.
Browse files Browse the repository at this point in the history
  • Loading branch information
autonomousapps committed Dec 3, 2024
1 parent c9e4d2e commit 34db3ec
Show file tree
Hide file tree
Showing 4 changed files with 20 additions and 3 deletions.
2 changes: 1 addition & 1 deletion gradle/libs.versions.toml
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ dagp = "2.4.2"
error-prone = "2.26.1"
gradle-publish-plugin = "1.1.0"
grammar = "0.3"
guava = "33.1.0-jre"
guava = "33.3.1-jre"
java = "11"
junit = "5.10.2"
kotlin = "1.9.25"
Expand Down
12 changes: 12 additions & 0 deletions graph-support/src/main/kotlin/com/autonomousapps/graph/Graphs.kt
Original file line number Diff line number Diff line change
Expand Up @@ -29,12 +29,24 @@ public object Graphs {
inDegree(it) == 0
}

/**
* Returns the list of nodes that have an in-degree of 0.
*/
public fun <N : Any> Graph<N>.roots(): List<N> = nodes().filter {
inDegree(it) == 0
}

/** Returns the nodes in this graph that are immediate [predecessors][Graph.predecessors] to [node]. */
public fun <N : Any> Graph<N>.parents(node: N): Set<N> = predecessors(node)

/** Returns the nodes in this graph that are immediate [successors][Graph.successors] to [node]. */
public fun <N : Any> Graph<N>.children(node: N): Set<N> = successors(node)

/** Returns a [ShortestPath] from [source] to any other node in [this][Graph] graph. */
public fun <N : Any> Graph<N>.shortestPaths(source: N): ShortestPath<N> {
return ShortestPath(this, source)
}

/**
* Returns an ordered list of nodes if there is a path from [source] to [target]. If there is no path, returns an
* empty list.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,11 @@ public class ShortestPath<N>(
}
}

/** Returns the distance from [source] to [other] if there is a path, otherwise null. */
public fun distanceTo(other: N): Int? {
return distTo[other]?.toInt()
}

public fun hasPathTo(other: N): Boolean {
val dist = distTo[other] ?: return false
return dist < Float.MAX_VALUE
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,11 +6,11 @@ import com.google.common.graph.Graph
import com.google.common.graph.Traverser
import java.util.*

/** With thanks to Algorithms, 4th Ed. See p582 for the explanation for why we want the reverse postorder. */
/** With thanks to Algorithms, 4th Ed. See p582 for the explanation of why we want the reverse postorder. */
@Suppress("UnstableApiUsage") // Guava graphs
public class Topological<N>(
graph: Graph<N>,
source: N
source: N,
) where N : Any {

public val order: Iterable<N>
Expand Down

0 comments on commit 34db3ec

Please sign in to comment.