array

Discussion in 'Programmer's Corner' started by braddy, Mar 19, 2006.

Dec 29, 2004
83
0
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.

Code ( (Unknown Language)):
1.
2. random=myrandom(n);
3. list[0]=random; /* initialized list[]*/
4. for(i=1;i<=n;i++)
5.  {random=myrandom(n);
6.    for(j=0;j<=i,j++) /* checking earlier elements*/
7. .......
8. .......(/* all I tried below to see if all elements ar different that what I need to add
9. does not work*/)
10. ........
11. ........
12.    if(list[j]!=random)
13.    random=myrandom(n);
14.   }
15.
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

2. Papabravo Expert

Feb 24, 2006
10,338
1,850
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.

3. hgmjr Moderator

Jan 28, 2005
9,030
214
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