Kore
Loading...
Searching...
No Matches
random.h
Go to the documentation of this file.
1#pragma once
2
3#include <kinc/global.h>
4
8
9#ifdef __cplusplus
10extern "C" {
11#endif
12
17KINC_FUNC void kinc_random_init(int64_t seed);
18
23KINC_FUNC int64_t kinc_random_get(void);
24
29KINC_FUNC int64_t kinc_random_get_max(int64_t max);
30
35KINC_FUNC int64_t kinc_random_get_in(int64_t min, int64_t max);
36
37#ifdef KINC_IMPLEMENTATION_MATH
38#define KINC_IMPLEMENTATION
39#endif
40
41#ifdef KINC_IMPLEMENTATION
42
43#include <limits.h>
44#include <stdlib.h>
45
46// xoshiro256** 1.0
47
48static inline uint64_t rotl(const uint64_t x, int k) {
49 return (x << k) | (x >> (64 - k));
50}
51
52static uint64_t s[4] = {1, 2, 3, 4};
53
54uint64_t next(void) {
55 const uint64_t result = rotl(s[1] * 5, 7) * 9;
56
57 const uint64_t t = s[1] << 17;
58
59 s[2] ^= s[0];
60 s[3] ^= s[1];
61 s[1] ^= s[2];
62 s[0] ^= s[3];
63
64 s[2] ^= t;
65
66 s[3] = rotl(s[3], 45);
67
68 return result;
69}
70
71void kinc_random_init(int64_t seed) {
72 s[0] = (uint64_t)seed;
73 s[1] = 2;
74 s[2] = 3;
75 s[3] = 4;
76 s[1] = next();
77 s[2] = next();
78 s[3] = next();
79}
80
81int64_t kinc_random_get(void) {
82 return (int64_t)next();
83}
84
85int64_t kinc_random_get_max(int64_t max) {
86 return kinc_random_get() % (max + 1);
87}
88
89int64_t kinc_random_get_in(int64_t min, int64_t max) {
90 int64_t value = kinc_random_get();
91 return (value < -LLONG_MAX ? LLONG_MAX : llabs(value)) % (max + 1 - min) + min;
92}
93
94#endif
95
96#ifdef __cplusplus
97}
98#endif
Provides basic functionality that's used all over the place. There's usually no need to manually incl...
KINC_FUNC int64_t kinc_random_get_in(int64_t min, int64_t max)
Returns a value between min and max (both inclusive).
KINC_FUNC int64_t kinc_random_get_max(int64_t max)
Returns a value between 0 and max (both inclusive).
KINC_FUNC int64_t kinc_random_get(void)
Returns a random value.
KINC_FUNC void kinc_random_init(int64_t seed)
Initializes the randomizer with a seed. This is optional but helpful.