Luis
Luis

Reputation: 2715

Random X Y coordinates

I want do get some random (x, y) coordinates, but I dont know how to do it. The coordinates must have a relative difference of 60 between each other.

For example, in pixels:

x    y
0    60
0    120
0    180
60   0
120  60
180  60
....

How can this be done using C#?

Upvotes: 1

Views: 4198

Answers (2)

Jason
Jason

Reputation: 421

You could do something like:

x = random(0, n)
if(x - 30 < 0)
    y = random(x + 30, n)
else if(x + 30 > n) 
    y = random(0, x - 30)
else 
    // in this case, x splits the range 0..n into 2 subranges.
    // get a random number and skip the "gap" if necessary
    y = random(0, n - 60);
    if(y > x - 30) {
        y += 60;

Make sense? It basically boils down to "pick 2 random numbers between 0 and n differing by more than 30." The above doesn't handle the case where n < 60.

Upvotes: 2

BlackBear
BlackBear

Reputation: 22979

Suppose you want those coordinates be in range 0 - n. Then you have to get a random number between 0 and n / 30 and multiply it by 30. So:

Random r = new Random();
coordinate_whatever = r.Next(n / 30) * 30;

Upvotes: 0

Related Questions