Reputation: 133
im struggling with this so long, i can fill my array with random numbers but they are not unique. I can't spot the problem in my code :( Can you help me? Thanks
int getUniqueNumber(int *p, int i)
{
int x,j,found;
do
{
x=rand()%100000 + 1;
found=0;
j=0;
while(j<=i && found==0)
{
if(p[i]==x)
found=1;
else
j++;
}
} while(found==1);
return x;
}
Upvotes: 0
Views: 94
Reputation: 311186
The function can be defined the following way
int getUniqueNumber( const int *p, int i )
{
int x, j;
do
{
x = rand() % 100000 + 1;
j = 0;
while ( j < i && p[j] != x ) ++j;
} while( j != i );
return x;
}
As for your function implementation then there are a wrong condition in the loop (j <= i )
while(j<=i && found==0)
and incorrect using of index i instead of index j
if(p[i]==x)
Upvotes: 0