Beefy Boxes and Bandwidth Generously Provided by pair Networks
"be consistent"
 
PerlMonks  

comment on

( [id://3333]=superdoc: print w/replies, xml ) Need Help??
For use in a shuffling algorithm, I need to be able to generate repeatable pseudo random sequences of integers in a range 1-N, such that given the same (integer) seed, the same sequence will always be produced.

I currently do:

srand($seed) ... $j = int rand ($n + 1); ...
inside a Fisher-Yates shuffle algorithm. This works, but also "taints" the random number generator by setting the seed to a deterministic value. Since this code runs under mod_perl, it is possible that later code will require a random number that is not so deterministically chosen, so I would like to avoid leaving the seed set to a deterministic value.

Is there a way to find out what the current seed is, so that I can restore it after generating the pseudo random sequence? Would calling srand() with no arguments after the deterministic sequence generation is complete be adequate, with regard to what perldoc -f srand says?

     Do not call "srand" multiple times in your program
     unless you know exactly what you're doing and why
     you're doing it.  The point of the function is to
     "seed" the "rand" function so that "rand" can pro­
     duce a different sequence each time you run your
     program.  Just do it once at the top of your pro­
     gram, or you won't get random numbers out of
     "rand"!

In reply to Generating Repeatable Pseudorandom Sequences by mp

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post; it's "PerlMonks-approved HTML":



  • Are you posting in the right place? Check out Where do I post X? to know for sure.
  • Posts may use any of the Perl Monks Approved HTML tags. Currently these include the following:
    <code> <a> <b> <big> <blockquote> <br /> <dd> <dl> <dt> <em> <font> <h1> <h2> <h3> <h4> <h5> <h6> <hr /> <i> <li> <nbsp> <ol> <p> <small> <strike> <strong> <sub> <sup> <table> <td> <th> <tr> <tt> <u> <ul>
  • Snippets of code should be wrapped in <code> tags not <pre> tags. In fact, <pre> tags should generally be avoided. If they must be used, extreme care should be taken to ensure that their contents do not have long lines (<70 chars), in order to prevent horizontal scrolling (and possible janitor intervention).
  • Want more info? How to link or How to display code and escape characters are good places to start.
Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others making s'mores by the fire in the courtyard of the Monastery: (3)
As of 2024-04-25 22:16 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found