Velocity Reviews > Sample Function / Random Permutations (newbie)

# Sample Function / Random Permutations (newbie)

Roland Rau
Guest
Posts: n/a

 08-22-2004
Dear all,

I am looking for a function in C which does the following:
After giving an array of n integers ranging from 1 to n, the function
should return a random sample of size k (k <= n) without replacement.
This is similar to take a random permutation of that array and then
choose the first k elements.

Some code example might clarify what I mean.

In R and S-Plus, the command would be:
sample(x=1:n, size = k, replace=FALSE)

In GNU Octave it would be (probably the same then in Matlab):
randperm(n)(1:k)

In Python, the command would be:
import random
random.sample(range(1,n+1), k)

I am pretty new to C, so I hope this is the correct forum to address
this question. I know this is nothing special, but I don't know so far
where to look up things for C (which is probably better than my first
humble approaches to implement such a function on my own).

Any advice is greatly appreciated (URLs, code fragments, ...).

Thanks,
Roland

Roland Rau
Guest
Posts: n/a

 08-22-2004
Roland Rau wrote:

>
> I am looking for a function in C which does the following:
> After giving an array of n integers ranging from 1 to n, the function
> should return a random sample of size k (k <= n) without replacement.
> This is similar to take a random permutation of that array and then
> choose the first k elements.
>

I guess I can manage myself now...
I assume the FAQ for comp.lang.c addresses part of this question
(Question 13.16 "How can I get random integers in a certain range?").
So I am pretty sure that the rest should be not much of a problem.
Sorry for bothering you,
Roland