Home > database >  Find a pair in a struct array only once
Find a pair in a struct array only once

Time:11-20

I have a struct and a struct array similar to this:

struct point{
    double x;
    double y;
    char name[10];
};
struct point points[1000];

I created an algorithm that calculates the distances between all the points and prints the pair with the smallest distance, like this:

    int count = 0;
    for (int i = 0; i < 1000; i  ){
        for(int j = 0; j < 1000; j  ){
            if(i != j){
                double distance = sqrt(pow(points[i].x - points[j].x, 2)   pow(points[i].y - points[j].y, 2));
                if(distance == min){
                    printf("%s - %s\n", points[i].name, points[j].name);
                    count  ;
                }
            }
        }
    }

If there are multiple pairs with the same distance, it prints all of them, but it prints them TWICE (the second time in a different order), what would be an ideal logical gate in the printing loop to prevent the structures with the same distance being printed twice?

CodePudding user response:

Change to this:

for (int i = 0; i < 999; i  ){
    for(int j = i 1; j < 1000; j  ){
        double distance = sqrt(pow(points[i].x - points[j].x, 2)   pow(points[i].y - points[j].y, 2));
        if(distance == min){
            printf("%s - %s\n", points[i].name, points[j].name);
            count  ;
        }
    }
}

I changed intervals for i and j and removed the if statement.

CodePudding user response:

Instead of looping like this:

for(int i = 0; i < 1000; i  ){
    struct point a = points[i]
    for(int j = 0; j < 1000; j  ){
        struct point b = points[j]
    }
}

Try this so that you only loop over each point once

for(int i = 0; i < 999; i  ){
    struct point a = points[i]
    for(int j = i; j < 1000; j  ){
        struct point b = points[j]
    }
}
  • Related