Search code examples
crandomsrand

Seeing the next four numbers in a random sequence (using srand and rand)


I seed my random number generator once, using srand(SEED) where SEED is just a 16 bit number generated by how long a button is pressed. I have my random number generator working just fine, but I need to be able to see the next four numbers in the sequence ahead of time, without disrupting anything if that makes sense.

So, I get the next number in the sequence by doing:

num = rand() % 4;

This gives me a random number between 0 and 3, which is great. Lets say the first 6 numbers are 0 3 2 1 2 3, and I just generated the first 3 in that sequence. The next four numbers are 2,1,2,3. I want to be able to get these numbers and display them, but calling rand() again will disrupt the original sequence (this is for a SIMON game, by the way. A cheat mode to look at the next things to press).

Calling srand(SEED) will bring me back to the first number, so I could easily see the first four numbers in the sequence without disrupting anything, but if I wanted to see numbers x -> x + 4, then it would mess it up.


Solution

  • Use something like this:

    int nextfourrand[4];
    
    int
    myrand (void);
    {
        int i;
        int r = nextfourrand[0];
        for (i = 0; i<=2; i++)
            nextfourrand[i] = nextfourrand[i+1];
        nextfourrand[3] = rand();
        return r;
    }
    

    and use this rather than rand(). Then on init, after srand() do:

    int i;
    for (i = 0; i<=3; i++)
        nextfourrand[i] = rand();
    

    Your next four random numbers are in the nextfourrand array.