Last active
August 29, 2015 13:59
-
-
Save nramsbottom/10485568 to your computer and use it in GitHub Desktop.
Simple random number generator.
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 <stdint.h> | |
| #include "rng.h" | |
| static uint32_t rng_current_seed = 0; | |
| rng * | |
| rng_create(uint32_t seed) { | |
| rng *r = malloc(sizeof(r)); | |
| r->seed = seed; | |
| r->gens = 0; | |
| return r; | |
| } | |
| void | |
| rng_free(rng *r) { | |
| if (r) | |
| free(r); | |
| } | |
| uint32_t | |
| rng_next(rng *r, uint32_t min, uint32_t max) { | |
| // reseed to the current generation | |
| if (rng_current_seed != r->seed) { | |
| rng_current_seed = r->seed; | |
| srand(rng_current_seed); | |
| uint32_t n = 0; | |
| while (n<r->gens) { | |
| rand(); | |
| n++; | |
| } | |
| } | |
| r->gens++; | |
| return rand() % (max - min) + min; | |
| } | |
| uint32_t | |
| rng_next0(rng *r, uint32_t max) { | |
| return rng_next(r, 0, max); | |
| } |
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 <stdint.h> | |
| typedef struct rng_t rng; | |
| struct rng_t { | |
| uint32_t seed; | |
| uint32_t gens; | |
| }; | |
| rng * | |
| rng_create(uint32_t seed); | |
| void | |
| rng_free(rng *r); | |
| uint32_t | |
| rng_next(rng *r, uint32_t min, uint32_t max); | |
| uint32_t | |
| rng_next0(rng *r, uint32_t max); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment