Created
October 1, 2015 18:41
-
-
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);
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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