# Finding nearest neighbor points

**URL:** <https://discourse.processing.org/t/finding-nearest-neighbor-points/29593>\
**Category:** Coding Questions\
**Created:** [April 24, 2021, 2:15am UTC](https://discourse.processing.org/t/finding-nearest-neighbor-points/29593 "2021-04-24T02:15:35Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![Mort](https://avatars.discourse-cdn.com/v4/letter/m/ce7236/32.png) [@Mort](https://discourse.processing.org/u/Mort)\
**Post date:** [April 24, 2021, 2:15am UTC](https://discourse.processing.org/t/finding-nearest-neighbor-points/29593/1 "2021-04-24T02:15:35Z")

</div>

Hi, I am having trouble with finding the nearest neighbor points. I am trying to create a web of lines connecting randomly generated points to each other. these lines are supposed to connect the nearest points to each other. Something like this

 ![20210423_220919](https://canada1.discourse-cdn.com/flex036/uploads/processingfoundation1/original/2X/8/82166bc29a1d7058ed569359d21a362f52fc8ef8.jpeg)

Instead, my code is doing a sort of all lines connect to the same point. Im not sure how to fix this.

> Point nodes = new Point[30];  
> float x1;  
> float x2;  
> float y1;  
> float y2;  
> float domain = 999999;  
> float dist;  
> int node1;  
> void setup(){  
> size(800,800);  
> background(255);  
> noFill();  
> strokeWeight(1);  
> //beginRecord(PDF, “PLan\_Drawing.pdf”);  
> for(int i = 0; i \< nodes.length; i++){  
> nodes[i] = new Point(random(width),random(height));  
> }  
> }  
> void draw(){  
> findNeighbours();  
> for (int i = 0; i \< nodes.length; i++){  
> findNeighbours();  
> }  
> }  
> class Point {  
> float x;  
> float y;  
> Point (float x\_, float y\_){  
> x = x\_;  
> y = y\_;  
> }  
> }  
> void findNeighbours(){  
> for (int i = 0; i \< nodes.length; i++){  
> for(int j = 0; j \< nodes.length; j++){  
> if(i != j){  
> dist = dist(nodes[i].x, nodes[i].y, nodes[j].x, nodes[j].y);  
> if(dist\<domain){  
> domain = dist;  
> node1 = j;  
> }  
> }  
> if(j == nodes.length-1){  
> line(nodes[i].x, nodes[i].y, nodes[node1].x, nodes[node1].y);  
> }  
> }  
> }  
> }

Any help is appreciated

---

<div class="post-metadata">

**Author:** ![TfGuy44](https://yyz2.discourse-cdn.com/flex036/user_avatar/discourse.processing.org/tfguy44/32/41_2.png) [@TfGuy44](https://discourse.processing.org/u/TfGuy44)\
**Post date:** [April 24, 2021, 3:36am UTC](https://discourse.processing.org/t/finding-nearest-neighbor-points/29593/2 "2021-04-24T03:36:36Z")

</div>

> [@Mort](#):
>
> void draw(){  
> findNeighbours();  
> for (int i = 0; i \< nodes.length; i++){  
> findNeighbours();  
> }  
> }

> [@Mort](#):
>
> void findNeighbours(){  
> for (int i = 0; i \< nodes.length; i++){  
> for(int j = 0; j \< nodes.length; j++){

That’s a lot of looping you’re doing… You need only compare each node to every other node. So a triple loop is too much!
