0

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;
}
RoastedCode
  • 133
  • 1
  • 2
  • 8
  • "*...they are not unique*" in which sense? – alk Mar 28 '15 at 16:44
  • Well if i printf the first 10 elements here's what i get: 5 6 7 10 11 11 12 12 13 14 there are same numbers in the array.. – RoastedCode Mar 28 '15 at 16:45
  • You should read [Unique random numbers in an integer array in the C programming language](http://stackoverflow.com/questions/1608181/unique-random-numbers-in-an-integer-array-in-the-c-programming-language) as well. – Arun A S Mar 28 '15 at 16:52

2 Answers2

4

p[i] == x should be p[j] == x.

JS1
  • 4,745
  • 1
  • 14
  • 19
0

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)
Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335