Beefy Boxes and Bandwidth Generously Provided by pair Networks
P is for Practical
 
PerlMonks  

Re: Re: Generating Repeatable Pseudorandom Sequences

by mp (Deacon)
on Sep 04, 2002 at 19:56 UTC ( #195184=note: print w/replies, xml ) Need Help??


in reply to Re: Generating Repeatable Pseudorandom Sequences
in thread Generating Repeatable Pseudorandom Sequences

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 (not 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.

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).

Thanks to input from dws above, here is the code I wound up using, which meets my requirements and avoids altering the seed used by rand().

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]; } }
Thank you all for the replies.

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://195184]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others cooling their heels in the Monastery: (3)
As of 2022-12-02 05:17 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?
    Notices?