I have an arraylist which stores coordinate points as objects, I also have created a formula to calculate the distance between these respective points. I need to store each point with their respective distances in a 2D arraylist. For example if I have points (1,2),(3,4),(5,6),(7,8) my 2D arraylist should store 3 distances for point (1,2), two distances for point (3,4) and one distance for point (7,8) if point (1,2) is my start point.
I have tried creating a nested for loop which keeps track of where my point is currently while simultaneously adding the distances in each index based on the sample point visited. However I get an Out of Bounds exception. I have verified that all points are stored correctly.
public static ArrayList<ArrayList<Double>> distance(ArrayList<sample_points> points) {
ArrayList<ArrayList<Double>> distArray =newArrayList<ArrayList<Double>>();
ArrayList<Double> distances = new ArrayList<Double>();
double dist = 0;
for(int i =0;i<points.size();i++){
distArray.add(new ArrayList());
}
for (int i = 0; i<points.size(); i++) {
//ArrayList<Double> distances = new ArrayList<>(); // convenience, you don't need the first loop only to populate the distArray lists
for(int j=i+1; j<points.size(); j++){
dist = Math.sqrt(
Math.pow(points.get(i).getX() - points.get(j).getX(), 2)
+ Math.pow(points.get(i).getY() - points.get(j).getY(), 2)
); // do your calculations here
distances.add(dist); // add the distance to the current distances list
}
distArray.add(distances); // add the current distances list to the result list
}
System.out.print("Your distances: "+ distarray)
return distArray;
}
Expected results: If number of sample points are 4 i.e (p1,p2),(p3,p4),(p5,6),(p7,p8) where p(i) are arbitrary points:
Your distances: [[d1,d2,d3],[d4,d5],[d6]] where d(i) are arbitrary distances
Actual results: Your distances: [[d1,d2,d3,d4],[d1,d2,d3,d4],[d1,d2,d3,d4][d1,d2,d3,d4]]