Sorting neighboring points by distance
in
Programming Questions
•
1 year ago
I am writing a program that involves a 2D array of points. Each point in the array needs to check the distance between itself and all the other points during the draw loop. The problem is I'm trying to order the resulting array so I can know the order of neighboring points from closest to farthest. The problematic code goes something like this:
- //Float array to store points and their properties
- float[][] e = new float[count][4];
- int count = 20;
- void setup(){
- //initialize point array
- for(int i =0; i< count; i++){
- e[i][0] = random(width); //x
- e[i][1] = random(height); //y
- e[i][2] = random(width); //targetX
- e[i][3] = random(height); //targetY
- }
- }
- void draw(){
- background(0,0);
- for(int i =0; i< e.length; i++){
- //sortByDist should pass in x, y, and the array of points
- //returns a 2D array where each row contains distance and the index of point in e
- //ex: neighbors[1] = {235, 2};
- float[][] neighbors = sortByDist(e[i][0], e[i][1], e);
- //limit j at number of neighbors line should be connected to
- //start at 1 since neighbor 0 will be itself (distance of 0)
- for(int j = 1; j < 4; j++){
- line(e[i][0], e[i][1], e[neighbors[j][1]][0], e[neighbors[j][1]][1]);
- }
- }
- }
2