Skip to content

Instantly share code, notes, and snippets.

@socantre
Created October 1, 2015 18:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save socantre/77ae716c2abc0a41725f to your computer and use it in GitHub Desktop.
Save socantre/77ae716c2abc0a41725f to your computer and use it in GitHub Desktop.
Find seeds that produce sequential states in rand(). e.g. find the seed that produces the same state as `srand(1); rand();`. In other words, find `x` such that the following prints `1`: `srand(1); rand(); int a = rand(); srand(x); int b = rand(); printf("%i", a == b);
#include <stdlib.h>
#include <stdio.h>
unsigned find_following_seed(unsigned seed) {
srand(seed);
(void)rand();
int arr[] = {rand(), rand(), rand(), rand()};
for (long long next_seed = 0; next_seed <= UINT_MAX; ++next_seed) {
srand(next_seed);
if (rand() == arr[0] && rand() == arr[1] && rand() == arr[2] &&
rand() == arr[3]) {
return next_seed;
}
}
fprintf(stderr, "Error: no seed following %u found.\n", seed);
abort();
}
int main() {
for (unsigned i = 0, next_seed, seed = 1; i < 10; ++i, seed = next_seed) {
next_seed = find_following_seed(seed);
printf("Seed following %u is %u.\n", seed, next_seed);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment