# array

Joined Dec 29, 2004
83
Hi gyus,
I need to write a function that fill an array (list[])of distinct integers following this algorithm:
1- get a random integer with a function myrandom.
2- See if the integer already appears in list[]; if not, put it in the next position available in perm.
then repeat 1 and 2 until the end of the array.

Rich (BB code):
random=myrandom(n);
list[0]=random; /* initialized list[]*/
for(i=1;i<=n;i++)
{random=myrandom(n);
for(j=0;j<=i,j++) /* checking earlier elements*/
.......
.......(/* all I tried below to see if all elements ar different that what I need to add
does not work*/)
........
........
if(list[j]!=random)
random=myrandom(n);
}
Please , can I have some suggestions especially on how to check if the earlier element of list are ALL DIFFERENT of the integer I want to add in list[].

Thank you

#### Papabravo

Joined Feb 24, 2006
19,016
Originally posted by braddy@Mar 19 2006, 02:01 PM
Hi gyus,
I need to write a function that fill an array (list[])of distinct integers following this algorithm:
1- get a random integer with a function myrandom.
2- See if the integer already appears in list[]; if not, put it in the next position available in perm.
then repeat 1 and 2 until the end of the array.

Rich (BB code):
random=myrandom(n);
list[0]=random; /* initialized list[]*/
for(i=1;i<=n;i++)
{random=myrandom(n);
for(j=0;j<=i,j++) /* checking earlier elements*/
.......
.......(/* all I tried below to see if all elements ar different that what I need to add
does not work*/)
........
........
if(list[j]!=random)
random=myrandom(n);
}
Please , can I have some suggestions especially on how to check if the earlier element of list are ALL DIFFERENT of the integer I want to add in list[].

Thank you
[post=15188]Quoted post[/post]​
When i == n you are done, the list is full. Don't use <= in the outer for loop

If none of the comparisons for j == 0 to j == i-1 find equality then random should be assigned to list Don't use <= in the inner loop

Unless the array gets very large, brute force is often the best algorithm especially if you can code it and debug it quickly, because your time is more valuable than the computer time. It was not always this way.

#### hgmjr

Joined Jan 28, 2005
9,027
What if you define a second array that has the same number of elements as the range of integers you will be using. For example, if your range of integers is 1 to 32 then define an array that contains 32 elements. Then as you obtain each integer from your random number generator, you would mark it used in this secondary array. That way you will not have to scan the storage array every time you retreive a new random integer.

hgmjr