calgorithmrandompermutation

C How to generate an arbitrary permutation within range [i,j]?


Does C standard library provide any function that generate a random permutation of consecutive numbers within a range?

How to make a function that efficiently does it? I'm thinking of making a random number generator that generates in a without-replacement way, but I could not figure out how to achieve minimum cost.

Note that, unlike most similar questions I found on web where all possible permutations are needed, here I just need ONE valid permutation, as long as the generation is not costly, and the permutation must be done in a random way, i.e., no tricks, say, simply return the ordered sequence or reversed sequence, etc.


Solution

  • Does C standard library provide any function that generate a random permutation of consecutive numbers within a range?

    No. The C standard library is intentionally small and utilitarian.* It does not contain such a function. You can undoubtedly find a third-party library that does this, though.

    How to make a function that efficiently does it? I'm thinking of making a random number generator that generates in a without-replacement way, but I could not figure out how to achieve minimum cost.

    The Fisher-Yates shuffle is a conventional way of doing this. It is exactly a sequence of (pseudo-)random selections without replacement, continuing until all the items have been selected. This costs O(n) in the number of items to shuffle / permute, and it can be done in-place. The linked Wikipedia article provides pseudocode for several variations. Yours could either receive (a pointer to) an array of the items to shuffle, or it could start by dynamically allocating an array of the right size, then populate deterministically, then shuffle.


    * Compared to many other high-level languages' standard libraries, such as C++'s, Python's, or Java's.