| |||||||||
![]() |
|
|
«
Previous Thread
|
Next Thread
»
|
Thread Tools | Search this Thread | Display Modes |
|
#1
|
|||
|
|||
|
Array
Hi guys,
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:
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 |
|
#2
|
|||
|
|||
|
I would use this kind of logic...
Code:
#define NUM_RANDOMS 10
int random = 0;
bool found = false;
int list[NUM_RANDOMS];
for (int i = 0; i < NUM_RANDOMS; ++i)
{
random = myrandom(n); //I'm assuming n is a seed
declared somewhere else in your code
found = false; //reset
for (int j = 0; j < i; ++j) //iterate thru the list up to now
{
if (list[j] == random) //if we find the current random number, set the variable found to true and stop iterating
{
found = true;
break;
}
}
if (!found) list[i] = random; //if it wasn't found, we can add the current random number to the list
}
|
|
#3
|
|||
|
|||
|
Initialization part is correct.
Here is my Algorithm: Code:
//After initializing list[]
//Assume that user is asked everytime to insert an elelment.
char reply;
reply = 'Y' ; //standing for yes and 'N' for No.
int j = 0, random = 0;
while( reply != 'N')
{
random = myrandom;
j = 0;
while( j != Length(list[]) )
if( list[j] == random )
break ;
else
j++;
if( j == Length ( list [] )
list[++j] == random;
else
{
cout<<"Continue? " ;
cin >> reply;
}
}
|
|
#4
|
|||
|
|||
|
Quote:
thanks guys!! |
![]() |
| Viewing: Dev Articles Community Forums > Programming > C/C++ Help > Array |
| Thread Tools | Search this Thread |
| Display Modes | Rate This Thread |
|
|
|
|
|