in reply to Randomize List of items
Clearly, if we pick items randomly from the original list without replacement, we will generate a completely random ordering of the list. That is what the following code effectively does.
It's a bit like pretending that we're making another list, but swapping things around using splice instead. Notice that the one guy that we never picked ends up as the first element in the array. Splice is cool.my @a = (1 .. 10); print join("\t", @a),"\n"; #starting from the end and working back for ($i = $#a; $i > 0; $i--) { # pick a random guy to stuff in the ith slot $guy = int(rand($i + 1)); #snatch the guy out, and stuff him in! splice(@a, $i, 0, splice(@a, $guy, 1)); } print join("\t", @a),"\n";
|
---|
Replies are listed 'Best First'. | |
---|---|
RE: RE: Randomize List of items
by johannz (Hermit) on May 26, 2000 at 19:55 UTC | |
RE: RE: Randomize List of items
by ZZamboni (Curate) on May 26, 2000 at 17:53 UTC |