With a run of 100,000, randomizing the alphabet, the distribution was mostly even, with a slight bias of items at the front of the list tending to wind up after the mid-point and items at the rear tending to wind up before the mid-point. For the 100,000 runs, the first item's average position was 1 past the mid-point, while the last item's average position was 1 before the mid-point. But this is close enough to a perfect shuffle for most uses.
my @lList = (1..10); my ($lPos, $lRand); # For every position in the list, swap it with a random # position earlier in the list. foreach $lPos (1..$#list) { $lRand = int(rand($lPos)); @lList[$lPos, $lRand] = @lList[$lRand, $lPos]; }
To correct the bias, use the following code:
my @lList = (1..10); my ($lPos, $lRand); # For every position in the list, swap it with a random # position earlier in the list. foreach $lPos (1..$#list) { $lRand = int(rand($lPos+1)); @lList[$lPos, $lRand] = @lList[$lRand, $lPos]; }
|
---|
Replies are listed 'Best First'. | |
---|---|
RE: Randomize List of items
by gregorovius (Friar) on May 19, 2000 at 09:47 UTC | |
RE: Randomize List of items
by KM (Priest) on May 26, 2000 at 18:11 UTC | |
RE: Randomize List of items
by athomason (Curate) on May 19, 2000 at 03:08 UTC | |
by Russ (Deacon) on May 19, 2000 at 03:48 UTC | |
by chromatic (Archbishop) on May 19, 2000 at 03:41 UTC | |
by johannz (Hermit) on May 19, 2000 at 03:58 UTC | |
by Russ (Deacon) on May 19, 2000 at 04:17 UTC | |
by turnstep (Parson) on May 19, 2000 at 16:21 UTC | |
RE: Randomize List of items
by Alokito (Novice) on May 26, 2000 at 08:57 UTC | |
by johannz (Hermit) on May 26, 2000 at 19:55 UTC | |
by ZZamboni (Curate) on May 26, 2000 at 17:53 UTC |