Skip to content

Instantly share code, notes, and snippets.

@bitsnaps
Created January 20, 2020 16:39
Show Gist options
  • Select an option

  • Save bitsnaps/8e5c02b382d40327550eecb40255f27a to your computer and use it in GitHub Desktop.

Select an option

Save bitsnaps/8e5c02b382d40327550eecb40255f27a to your computer and use it in GitHub Desktop.
jGrapht using groovy example
@Grab('org.jgrapht:jgrapht-core:1.3.1')
import org.jgrapht.*
import org.jgrapht.graph.*
import org.jgrapht.io.*
import org.jgrapht.traverse.*
class Main {
static void main(args){
Graph<String, DefaultEdge> stringGraph = createStringGraph()
// note undirected edges are printed as: {<v1>,<v2>}
println("-- toString output")
println(stringGraph.toString())
println()
// create a graph based on URI objects
Graph<URI, DefaultEdge> hrefGraph = createHrefGraph()
// find the vertex corresponding to www.jgrapht.org
// URI start = hrefGraph.vertexSet().stream().filter(uri -> uri.getHost().equals("www.jgrapht.org")).findAny().get()
URI start = hrefGraph.vertexSet().find{ uri -> uri.getHost() == "www.jgrapht.org"}
// perform a graph traversal starting from that vertex
println("-- traverseHrefGraph output")
traverseHrefGraph(hrefGraph, start)
println()
println("-- renderHrefGraph output")
renderHrefGraph(hrefGraph)
println('done.')
}
static Graph<URI, DefaultEdge> createHrefGraph(){
Graph<URI, DefaultEdge> g = new DefaultDirectedGraph<>(DefaultEdge)
URI google = new URI("http://www.google.com")
URI wikipedia = new URI("http://www.wikipedia.org")
URI jgrapht = new URI("http://www.jgrapht.org")
// add the vertices
g.addVertex(google)
g.addVertex(wikipedia)
g.addVertex(jgrapht)
// add edges to create linking structure
g.addEdge(jgrapht, wikipedia)
g.addEdge(google, jgrapht)
g.addEdge(google, wikipedia)
g.addEdge(wikipedia, google)
return g
}
static void traverseHrefGraph(Graph<URI, DefaultEdge> hrefGraph, URI start)
{
new DepthFirstIterator<>(hrefGraph, start).each { uri ->
println(uri)
}
}
static void renderHrefGraph(Graph<URI, DefaultEdge> hrefGraph)
{
// use helper classes to define how vertices should be rendered,
// adhering to the DOT language restrictions
def vertexIdProvider = { it.host.replace('.', '_') }
def vertexLabelProvider = { it.toString() }
// Error cannot find class GraphExporter
/*GraphExporter<URI, DefaultEdge> exporter =
new DOTExporter<>(vertexIdProvider, vertexLabelProvider, null)
Writer writer = new StringWriter()
exporter.exportGraph(hrefGraph, writer)
println(writer.toString())*/
}
static Graph<String, DefaultEdge> createStringGraph()
{
Graph<String, DefaultEdge> g = new SimpleGraph<>(DefaultEdge)
String v1 = "v1"
String v2 = "v2"
String v3 = "v3"
String v4 = "v4"
// add the vertices
g.addVertex(v1)
g.addVertex(v2)
g.addVertex(v3)
g.addVertex(v4)
// add edges to create a circuit
g.addEdge(v1, v2)
g.addEdge(v2, v3)
g.addEdge(v3, v4)
g.addEdge(v4, v1)
return g
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment