Search code examples
javaprocessingjgraphtdigraphs

Return number of edges of each vertex in a digraph (jgrapht)


I have a digraph created using:

    public static DirectedGraph<Point, DefaultEdge> directedGraph = new DefaultDirectedGraph<Point, DefaultEdge>(DefaultEdge.class);

 void setup() { 

  Point myPoint = new Point(x, y);
  Point myNextPoint = new Point(xToFillNext, yToFillNext);
  directedGraph.addVertex(myPoint);
  directedGraph.addVertex(myNextPoint);
  directedGraph.addEdge(myPoint, myNextPoint);

  Point mySecondPoint = new Point(x, y);
  Point mySecondNextPoint = new Point(xToFillNext, yToFillNext);
  directedGraph.addVertex(mySecondPoint);
  directedGraph.addVertex(mySecondNextPoint);
  directedGraph.addEdge(mySecondPoint, mySecondNextPoint);

System.out.println("#vertices: "+ directedGraph.vertexSet());

}

 public static class Point {

  public int x;
  public int y;

  public  Point(int x, int y) 
  {

    this.x = x;
    this.y = y;
  }
  @Override
    public String toString() {
    return ("[x="+x+" y="+y+"]");
  }

  @Override
public int hashCode() {
    int hash = 7;
    hash = 71 * hash + this.x;
    hash = 71 * hash + this.y;
    return hash;
}



@Override
public boolean equals(Object other) 
{
    if (this == other)
       return true;

    if (!(other instanceof Point))
       return false;

    Point otherPoint = (Point) other;
    return otherPoint.x == x && otherPoint.y == y;
}
}

I would like to get the number of outwards edges per vertex using:

directedGraph.outDegreeOf()

but I don't want to do it vertex per vertex (this is a simple code to make it easier to go through it, in my whole program I have many more vertices) and I'd like to go through the vertex set and return the number of outwards edges for each vertex of the set automatically, no matter how many vertices there are.

How should I proceed to do this ?

(I use processing which is based on java)


Solution

  • Check out the JGrapht API.

    The DirectedGraph interface contains a vertexSet() function. You can use this to iterate over the vertexes you've added, and you can get the outDegreeValue() of each one:

    for(Point p : directedGraph.vertexSet()){
       int degree = directedGraph.outDegreeOf(p);
       System.out.println("Degree of " p.toString() + ": " + degree);
    }