# how to: Non repeated random #s

• 03-08-2006
ypramesh
how to: Non repeated random #s
I am trying to generate random numbers to fill in a 2-D array but they can not repeat within the array

for example I have a 10*10 array and i want to fill array with 1-100 randomly, without repeating elements (So I will have to use all 1-100#s)
:(
Thankx
• 03-08-2006
ssharish2005
well, u got have a if statmnet in between to check that it don't repeat again. thats the only way u can do that. make sure u call srand() fucntion before calling the random() fucntion. otherwise u get the same sequence of numbers all the time where u call it.

sshairsh2005
• 03-08-2006
Cactus_Hugger
Here's what I did with my calculator:

Make a list of your numbers, 1-100, in order. Keep a number that says how many are in that list, I'll call it 'ltotal'. Set ltotal to 100 to start with. Now, loop through your array in order, like myarray[0][0], myarray[0][1], etc. For each space in that array, generate a random number from 0 to ltotal - 1. (_not_ from 1 to 100) Use the random number you've just got as an index to select a number out of your list, like ordered_numbers[random_number(0, ltotal - 1)]. Save that number to the 2D array. Then, swap that number with the number at the end of the list. Shrink the list (ltotal) by 1. Repeat.

Essentially, your picking a number from a list of 1 - 100 at random, swapping it with the last item, and shrinking the list. (To remove the number you just picked from the list) (Since there is no point in keeping the list in order.) This keeps you from checking if you've already generated the number, since you haven't.

Hope that helps!