RoastedCode
RoastedCode

Reputation: 133

Assign unique random integers in an array (C)

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

Answers (2)

Vlad from Moscow
Vlad from Moscow

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

JS1
JS1

Reputation: 4767

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

Upvotes: 4

Related Questions