Maintain random seed for duration of session

628 views Asked by At

Background: If you seed your prng, it will print out the same random sequence. So, if I tell you that I used the seed 123 and I got 1, 5, 2, 4. Then, you can use the seed 123 and get 1, 5, 2, 4.

What I want to do in the most simple case... I make a web page that lets you enter a seed. Then, it shows you one random number and a "next" link. You click the next link and get the next random number. The problem is that the page accessed when clicking "next" has no relationship with the previous page. So, it is not based on the seed entered.

What I'm trying to do, and I am obviously overlooking something, is to maintain the seed during the session. I can srand to seed the rand for the first random number. Then, I need to store the updated seed in the session so the next time the user shows up I can srand with the proper next seed. Is there an opposite to srand? I don't want to seed the rand. I want to get the value required to make it start in the current state the next load.

1

There are 1 answers

1
Mat On BEST ANSWER

You can workaround your issue by always reinitializing the srand with the last random number generated. You "mix up" the seeds but you still have a reproducable way to generate random numbers.

Here is some code :

function getNextRandomNumber()
{
    $mySeed = 0; // a default seed value
    if (isset($_SESSION['seed']))
    {
        // continue our seed serie
        $mySeed = $_SESSION['seed'];
    }
    else if (isset($_GET['seed']))
    {
        // reinitialize the seed serie with a user's value
        $mySeed = $_GET['seed'];
    }
    // reproducable srand value
    srand($mySeed);

    // generate the random number
    $rand = rand();
    // We save the seed
    $_SESSION['seed'] = $rand;

    return $rand;
}