1

So I'm using the JGraphT library and I have a method already to create a two-directional edges in my program.

However when I display the graph, it currently displays the return direction like so:

D1 -> D2
D2 -> D1

When I would prefer it to be as follows:

D1 <-> D2

Here is the code that I am using so far:

for(String vertex : destinations) {
    Set<DefaultWeightedEdge> edges = graph.outgoingEdgesOf(vertex);
    for(DefaultWeightedEdge edge : edges) {
        System.out.println(graph.getEdgeSource(edge) + " -> " + graph.getEdgeTarget(edge));
    }
}

For reference this is the destinations list that i use:

ArrayList<String> destinations = new ArrayList<String>();
destinations.add("Amsterdam");
destinations.add("Boston");
destinations.add("Chicago");
destinations.add("Edinburgh");
destinations.add("Heathrow");
destinations.add("Hong Kong");
destinations.add("Montreal");
destinations.add("New Delhi");
destinations.add("Shanghai");
destinations.add("Toronto");
madcrazydrumma
  • 1,847
  • 3
  • 20
  • 38

1 Answers1

1

May be not the nicest code:

for (String source: destinations) {
    Set<DefaultWeightedEdge> edges = graph.outgoingEdgesOf(source);
    for (DefaultWeightedEdge edge : edges) {
        //String source = graph.getEdgeSource(edge);
        String target = graph.getEdgeTarget(edge);
        boolean comingBack = graph.containsEdge(target, source);
        if (comingBack && source.compareTo(target) > 0) {
            continue; // Skip B <-> A as already A <-> B.
        }
        String arrow = comingBack ? "<->" : "->";
        System.out.printf("%s %s %s%n", source, arrow, target);
    }
}
Joop Eggen
  • 107,315
  • 7
  • 83
  • 138
  • It doesn't actually work, it is still producing the same (if not very similar) output: `Boston -> Chicago, Boston -> Montreal, Chicago -> Boston` – madcrazydrumma Nov 23 '15 at 11:36
  • I messed a bit around as you probably saw. `graph.outgoingEdgesOf(target).contains(source)` or `graph.incomingEdgesOf(source).contains(target)` or best `graph.containsEdge(target, source)` should do if your graph's vertex type is String. – Joop Eggen Nov 23 '15 at 11:45
  • Okay `graph.containsEdge(target, source)` does work, however it adds this to the output: `Boston -> Boston, Boston -> Boston, Boston -> Boston` – madcrazydrumma Nov 23 '15 at 11:47
  • I see you edited it after what I commented! Works perfectly now, thank you Joop :) – madcrazydrumma Nov 23 '15 at 11:51