Search code examples
carraysrandomsrand

How to pick a random number from a list, only once, using C


So i have an array of integers that go from 0 to 27.

for(i<0; i<28; i++)
{
    ListId[i] = i;
}

What I want to do is to pick a number from that array and re-order it in another array, randomly.

I've tried to replaced the number already picked, by a flag, the number -1:

for(i<0; i<28; i++)
{
    RandomId[i] = i;
    ListId[i] = i;
}

srand(time(NULL));

for(i=0; i<28; i++)
{
    res = rand() % 27;
    aux = ListId[res];

    if (ListId[res] != -1)
    {
        RandomId[i] = aux;
        ListId[res] = -1;
    }
    else
        i--;
}

printf("New list of integers: ");

for(i=0; i<28; i++)
{
    printf("%d | ", RandomId[i]);
}

But in ends into an infinite loop.

Hope someone can help me.

Thank you in advance


Solution

  • Notice your first for loop: for(i<0;i<28;i++)

    And notice your: res = rand() % 27; ... should be 28.

    The range of % N is 0 to (N-1), hence your 27 results with the range 0-26.