Skip to content

Instantly share code, notes, and snippets.

@nramsbottom
Last active August 29, 2015 13:59
Show Gist options
  • Select an option

  • Save nramsbottom/10485568 to your computer and use it in GitHub Desktop.

Select an option

Save nramsbottom/10485568 to your computer and use it in GitHub Desktop.
Simple random number generator.
#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);
}
#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