Random Number Generator Problem

Associate
Joined
13 Oct 2004
Posts
1,243
Hey,

I'm trying to generate n number of coordinates (X and Y) randomly. Each time it generates a set of X and Y coordinates, it checks an array to see if they've already been chosen previously. If they haven't then they're added to the array. If they have then it generates a new set of coordinates and does the same check. It loops until a unique set is chosen.

The problem I'm having is that there's a set number of coordinates it can choose from (1,1 to 2,8 - So 16 in total). I'm finding that if it needs to choose less than about 4 coordinates, then it works fine. But if the number is larger, it tends to exceed the script's maximum execution time.

I can see why this is happening. As the coordinates get chosen and added to an array, there's less of a chance of the random number generator picking a unique one each time round, so it loops more and more times. It will EVENTUALLY pick one, but the length of time it takes to pick it gets longer as they fill up.

Has anyone got any ideas how to solve this? I'm doing it in PHP, but I imagine the problem is the same regardless of the language.

(I hope I've explained this alright...)

Xen :(
 
Thanks for that, that seems to work! :D

One question though, I don't understand why! Your code is very similar to what I had (A while loop that looped infinitely until it got unique coordinates), yet yours causes no problems whereas mine took an age to execute and get unique coordinates.

Nevermind, it works. Cheers. :p
 
Back
Top Bottom