JustTryingToCode
JustTryingToCode

Reputation: 119

Finding Nearest Points is not returning right answer

I have to find the points that are the closest to each other. I wrote my code and it should work (I did it in java, and it worked fine, and then I translated it to C).

The C program keeps printing out the wrong answer (0.0) (0.0).

The right answer is (1.0, 1.0) (2.0, 0.5)

enter image description here

#include <stdio.h>
#include <stdlib.h>
#include <math.h>

double nearest(double x1, double y1, double x2, double y2);

int main(){
    double temp1 = 0;
    double temp2 = 0;
    double temp3 = 0;
    double temp4 = 0;

    double points[8][2] = {
        {-1, 3},
        {-1, -1},
        {1, 1},
        {2, 0.5},
        {2, -1},
        {3, 3},
        {4, 2},
        {4, -0.5}
    };

    double minimum = nearest(points[0][0], points[0][1], points[1][0], points[1][1]);

    for(int i = 0; i < 8; i++){
        for(int j = i+1; j < points[i][j]; j++){
            double distance = nearest(points[i][0], points[i][1], points[j][0], points[j][1]);

            if(minimum > distance){
                minimum = nearest(points[i][0], points[i][1], points[j][0], points[j][1]);

                temp1 = points[i][0];
                temp2 = points[i][1];
                temp3 = points[j][0];
                temp4 = points[j][1];
            }
        }
    }
    printf("(%lf, %lf) (%lf, %lf)\n", temp1, temp2, temp3, temp4);
}

double nearest(double x1, double y1, double x2, double y2){
    return sqrt((pow(x2 - x1, 2)) + (pow(y2 - y1, 2)));
}

Upvotes: 0

Views: 29

Answers (1)

Ackdari
Ackdari

Reputation: 3498

There are two major problems in for code:

  1. If the two first points in the set are the closest you will never change the value for your temp variables. I would also suggest to not hold the xy values in temp variables but the indices of the (so far) closest points.
  2. In the second for loop you check for j < points[i][j] which is not correct. It should be j < 8.

I would also suggest that the check for the first loop should be i < 7 becauese for i = 7 you dont have to check any distance.

Upvotes: 2

Related Questions