note
mp
Sorry if I was unclear. The requirements are not mutually exclusive, I just need different types of "random" numbers at different places in the code. The shuffling subroutine needs to use a deterministic sequence of pseudo random (<b>not</b> truly random) numbers that are repeatable given the same seed. Other code outside the shuffle algorithm may eventually need to use random numbers based on rand() that are not repeatable like those used in the shuffle algorithm. Since this is a rather large persistent (mod_perl) application, it is difficult to foresee where rand() will be used in other code outside the shuffle subroutine, so I would like to avoid "tainting" it with a deterministic seed, or at least clean up afterwards by using a good seed.
<p>What I am writing is a shuffle that can be seeded to always produce exactly one permutation per seed, but that when run with different seeds (seeds that are sequential integers, with some gaps) will produce a set of permutations that are reasonably uniformly distributed. I.e., if I sort the array qw(a b c d) 2400 times using 2400 different seeds, I should expect to see each of the 24 possible permutations about 100 times (plus/minus some tolerance).
<p>Thanks to input from [id://22308] above, here is the code I wound up using, which meets my requirements and avoids altering the seed used by rand().
<code>
use Math::Random::MT ();
sub shuffle {
my $self = shift;
my $seed = shift;
my $array = $self;
# ||rand() in case no seed passed to shuffle algorithm
my $mt = Math::Random::MT->new( $seed || rand );
my $i;
for($i = @$array; --$i; ) {
my $j = int( $mt->rand($i + 1) );
@$array[$i, $j] = @$array[$j, $i];
}
}
</code>
Thank you all for the replies.
195149
195172