in reply to random elements with fixed totals

I think this is in Knuth, but I'm too lazy to look it up. Assuming that $N and $M are set:
my @a = map {my $e = rand $N -- < $M; $e && $M --; $e || 0} 1 .. $N;

Abigail

Replies are listed 'Best First'.
Re: Re: random elements with fixed totals
by ysth (Canon) on Nov 16, 2003 at 07:21 UTC
    I looked in Knuth before asking and didn't see it.

    But that is just the algorithm I am worried will distort the distribution at the end! For instance, if M is one, the probability of the first element being set is 1/N, but the probability of the last element being set is ...

    (N-1)!/N!     Oh. (Whacks self on head.)

    Knuth 3.4.2 Random Sampling and Shuffling, Algorithm S
    Thanks, Abigail