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]; }
In reply to Randomize List of items by johannz
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |