Xorshift32
This commit is contained in:
9
iris_c/main.c
Normal file
9
iris_c/main.c
Normal file
@@ -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;
|
||||
}
|
||||
24
iris_c/random.c
Normal file
24
iris_c/random.c
Normal file
@@ -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;
|
||||
}
|
||||
10
iris_c/random.h
Normal file
10
iris_c/random.h
Normal file
@@ -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