Xorshift32
This commit is contained in:
@@ -0,0 +1,9 @@
|
|||||||
|
#include "random.h"
|
||||||
|
#include <stdio.h>
|
||||||
|
|
||||||
|
int main() {
|
||||||
|
set_random_seed(1842);
|
||||||
|
uint32_t num = random_u32();
|
||||||
|
printf("%u\n", num);
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
@@ -0,0 +1,24 @@
|
|||||||
|
#include "random.h"
|
||||||
|
|
||||||
|
static uint32_t state = 1;
|
||||||
|
|
||||||
|
void set_random_seed(uint32_t seed) {
|
||||||
|
state = seed ? seed : 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
uint32_t random_u32(void) {
|
||||||
|
state ^= state << 13;
|
||||||
|
state ^= state >> 17;
|
||||||
|
state ^= state << 5;
|
||||||
|
return state;
|
||||||
|
}
|
||||||
|
|
||||||
|
uint32_t random_range(uint32_t max) {
|
||||||
|
if (max == 0) return 0;
|
||||||
|
uint32_t threshold = (0xFFFFFFFFU / max) * max;
|
||||||
|
uint32_t r;
|
||||||
|
do {
|
||||||
|
r = random_u32();
|
||||||
|
} while (r >= threshold);
|
||||||
|
return r % max;
|
||||||
|
}
|
||||||
@@ -0,0 +1,10 @@
|
|||||||
|
#ifndef RANDOM_H
|
||||||
|
#define RANDOM_H
|
||||||
|
|
||||||
|
#include <stdint.h>
|
||||||
|
|
||||||
|
void set_random_seed(uint32_t seed);
|
||||||
|
uint32_t random_u32(void);
|
||||||
|
uint32_t random_range(uint32_t max);
|
||||||
|
|
||||||
|
#endif
|
||||||
Reference in New Issue
Block a user