user6216509
user6216509

Reputation:

comparing pairs of vertices in java

I want to traverse through all the vertices from a given set of vertices and compare the distance between two pairs. Suppose my vertices list is as follows:

(1,2),(3,4),(5,6),(7,8),(9,10),(11,12)

I want to traverse the set of vertices in the following way:

1st iteration:

for pair (1,2) and (3,4) I want to compare it with [(5,6),(7,8)],[(7,8),  (9,10)]and[(9,10),(11,12)]

2nd iteration:

for pair (3,4) and (5,6) I want to compare it with [(7,8),(9,10)]and[(9,10),(11,12)]

3rd iteration:

for pair (7,8) and (9,10) I want to compare it with [(9,10),(11,12)]

how will I do this using nested loop in java? I want to store the set of vertices in an arraylist. I have tried in the following way but getting exception:

 for(i=0;i<arraylist.size();i++)
 {
     for(j=i+2;j<arraylist.size();j++
      {
           //x,y,u,v are objects of the vertex class
             x=arraylist.get(i);
             y=arraylist.get(i+1);
             u=arraylist.get(j);
             v=arraylist.get(j+1);

       }
  }

What additional change will I need to make in the above code fragment to traverse the vertex set as I explained above?

Upvotes: 1

Views: 273

Answers (1)

Rob Audenaerde
Rob Audenaerde

Reputation: 20019

You get an IndexOutOfBoundsException exception, because you try go get() items with index that are not in the list (see Arraylist.get() )

 j<arraylist.size()

 v=arraylist.get(j+1);  <- (j+1) can become arraylist.size().

So you should limit your loops to:

  j<arraylist.size()-1

Upvotes: 3

Related Questions