Vandib
Vandib

Reputation: 25

Generating random coordinates with differences between them

So i seek to generate 5 random coordinates within an area of roughly 640,000 points with each axis value between 100 and 900. These coordinates must have a distance of more than 100 between them to prevent an overlap. Having searched previous answers and attempted a piece of code below:

struct point
    {
        int x;
        int y;
    };

    point pointarray[6];
    srand ( time(NULL) );
    pointarray[1].x = 100+(std::rand()% 801);
    pointarray[1].y = 100+(std::rand()% 801);
    for (int n=2; n <= 5 ; n++)
    {
        double dist;
        int currentx;
        int currenty;
        double xch;
        double ych;
        while (dist < 100)
        {
            srand ( time(NULL) );
            currentx = (100+(std::rand()% 801));
            currenty = (100+(std::rand()% 801));

            xch = (currentx - (pointarray[(n-1)].x));
            ych = (currenty - (pointarray[(n-1)].y));
            dist = sqrt(xch*xch + ych*ych);
            if (dist >= 100 && dist <= 800 )
            {
                currentx = pointarray[n].x;
                currenty = pointarray[n].y;
            }
        }
    }

I do not understand why the last 4 points are absolutely huge numbers (in the millions) while only the first is within the required range?

Upvotes: 0

Views: 249

Answers (1)

AlexD
AlexD

Reputation: 32566

You use uninitialized dist, it could be the problem:

double dist;
....
while (dist < 100)

Also, I see no place where you write to pointarray (except pointarray[1]). Should not

currentx = pointarray[n].x;

become

pointarray[n].x = currentx;

Also, if dist gets bigger than 800, then nothing happens and we just go to the next element. I guess the intention was to stay within while loop instead.

Also, we check the distance to one previous point. I'm not sure, but it could be that the intention was to check distances to all previous points. In the latter case, we need an inner loop perhaps. But make sure that there is no possibility that already placed points make it impossible to put the next one.

Also, perhaps you do not want the second srand ( time(NULL) );

Upvotes: 1

Related Questions