简体   繁体   中英

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.

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.

I guess I can just call srand(SEED), and then call rand() an appropriate amount of times to get back to where I was. It's kind of messy and inefficient, but it definitely works. And considering this is a SIMON game, the most times I'd have to call rand() in a row to get back to where the player was is like, 30 or so anyways.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM