Generate "In-Range" Random Numbers in C

c

Solution

The algorithm in Richard J. Ross's answer is incorrect. It generates `n^n` possible orderings instead of `n!`. This post on Jeff Atwood's blog illustrates the problem: http://www.codinghorror.com/blog/2007/12/the-danger-of-naivete.html

Instead, you should use the Knuth-Fisher-Yates Shuffle:

int values[11] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
srand(time(NULL));

for (int i = 10; i > 0; i--)
{
    int n = rand() % (i + 1);

    int temp = values[n];
    values[n] = values[i];
    values[i] = temp;
}

Problem

I need to generated random numbers in the range [0, 10] such that: - All numbers occur once. - No repeated results are achieved. Can someone please guide me on which algorithm to use?

Original source

Related problems