Is it possible to look into the following rand value

Assuming the generator has been seeded, is it possible to peer into the next random value without changing it?

i.e. Given:

#include <stdlib.h>

int r;
r = rand(); // say this is 99
r = rand(); // say this is 80

      

Is it possible

#include <stdlib.h>

int r;
r = peekAtRand(); // this will give 99
r = rand(); // but this still gives 99

r = peekAtRand(); // this will give 80
r = rand(); // but this still gives 80

      

Also, can this be expanded to look at the next n numbers ?

+3


source to share


4 answers


You can implement peekAtRand

like this:

int peekAtRand()
{
    int r,s;
    s = rand();
    srand(s);
    r = rand();
    srand(s);
    return r;
}

      



To make it "decent", call it srand((unsigned int)time(NULL))

at the beginning of your program.

+2


source


This is not possible in the current implementation of most random number generators. But there are two solutions for this.

Solution 1

If you set the initial value of a random number generator using a function srand()

with the same value, you will always get the same sequence of numbers. This way you can easily predict the number in the second pass.



Solution 2

Just write a small buffer for numbers.

const int randBufferSize = 1024;
int randBuffer[randBufferSize];
int randBufferPosition = 0;

// Initialise the buffer with random data.
void initRandBuffer() {
    for (int i = 0; i < randBufferSize; ++i) {
        randBuffer[i] = rand();
    }
}

// Peek at the n'th random number (starting from 0).
int peekAtRand(int n) {
    int peekIndex = randBufferPosition + n;
    if (peekIndex >= randBufferSize) {
        peekIndex -= randBufferSize;
    }
    return randBuffer[peekIndex];
}

// Get the next random number.
int getRand() {
    int result = randBuffer[randBufferPosition];
    randBuffer[randBufferPosition] = rand();
    ++randBufferPosition;
    if (randBufferPosition >= randBufferPosition) {
        randBufferPosition = 0;
    }
}

      

+6


source


int peek;
int r;

peek = rand();
doPeekyThings(peek);
r = peek;

      

+4


source


Assuming the generator has been seeded, is it possible to peer into the next random value without changing it?

Do not use it rand()

yourself. You need to buffer it.

Also, can this be expanded to look at the next n numbers?

If you buffer it, then yes:

const int bufsize = 15;
int randarr[bufsize];
int cur_rand = 0;

int my_srand(int seed) {
  srand(seed);
  for (int i=0;i<bufsize;++i) {
    randarr[i] = rand();
  }
}

int my_rand() {
  int r = randarr[cur_rand];
  randarr[cur_rand] = rand();
  ++cur_rand;
  if (cur_rand >= bufsize) cur_rand = 0;
  return  r;
}

int peek_my_rand(int n = 0) {
  return randarr[(cur_rand + n)%bufsize];
}

      

With this implementation, you will always have numbers bufsize

to peek at, and peeking will never mess with the actual generator, meaning it will never change its internal state.

+2


source







All Articles