-
Notifications
You must be signed in to change notification settings - Fork 6
/
random.c
35 lines (32 loc) · 850 Bytes
/
random.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
#include "param.h"
#include "types.h"
#include "defs.h"
// Return a integer between 0 and ((2^32 - 1) / 2), which is 2147483647.
uint
random(void)
{
// Take from http://stackoverflow.com/questions/1167253/implementation-of-rand
static unsigned int z1 = 12345, z2 = 12345, z3 = 12345, z4 = 12345;
unsigned int b;
b = ((z1 << 6) ^ z1) >> 13;
z1 = ((z1 & 4294967294U) << 18) ^ b;
b = ((z2 << 2) ^ z2) >> 27;
z2 = ((z2 & 4294967288U) << 2) ^ b;
b = ((z3 << 13) ^ z3) >> 21;
z3 = ((z3 & 4294967280U) << 7) ^ b;
b = ((z4 << 3) ^ z4) >> 12;
z4 = ((z4 & 4294967168U) << 13) ^ b;
return (z1 ^ z2 ^ z3 ^ z4) / 2;
}
// Return a random integer between a given range.
int
randomrange(int lo, int hi)
{
if (hi < lo) {
int tmp = lo;
lo = hi;
hi = tmp;
}
int range = hi - lo + 1;
return random() % (range) + lo;
}