假设生成器已播种,可以在不更改的情况下查看下一个随机值?
即给出:
#include <stdlib.h>
int r;
r = rand(); // say this is 99
r = rand(); // say this is 80
Run Code Online (Sandbox Code Playgroud)
这可能吗
#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
Run Code Online (Sandbox Code Playgroud)
此外,这可以扩展到下一个n号码偷看吗?
对于大多数随机数生成器的当前实现,这是不可能的.但是有两个解决方案.
如果将使用该srand()函数的随机数生成器的起始值设置为相同的值,则始终会获得相同的数字序列.这样,您可以轻松预测第二遍中的数字.
简单地为数字写一个小缓冲区.
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;
}
}
Run Code Online (Sandbox Code Playgroud)