-
Notifications
You must be signed in to change notification settings - Fork 1
/
rand.c
55 lines (48 loc) · 1.19 KB
/
rand.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
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
/**
* Generating random numbers in C using simple rand() function
* gcc -o rand -Wall rand.c
*/
#include <time.h>
#include <stdlib.h>
#include <stdio.h>
#include <assert.h>
#include <unistd.h>
/**
* Returns an integer in the range [0, n).
*
* Uses rand(), and so is affected-by/affects the same seed.
*/
int randint(int n) {
if ((n - 1) == RAND_MAX) {
return rand();
} else {
// Chop off all of the values that would cause skew...
long end = RAND_MAX / n; // truncate skew
assert (end > 0L);
end *= n;
// ... and ignore results from rand() that fall above that limit.
// (Worst case the loop condition should succeed 50% of the time,
// so we can expect to bail out of this loop pretty quickly.)
int r;
while ((r = rand()) >= end);
return r % n;
}
}
#define BUFSIZE 1024
int main(int argc, char * argv[]){
if (argc == 1){
srand(0);
} else {
srand(atoi(argv[1]));
}
// Generates random numbers ad infinitum.
char buff[BUFSIZE];
for(;;){
for(int i = 0; i<BUFSIZE; i++){
buff[i] = randint(256);
}
write(fileno(stdout), buff, BUFSIZE);
fflush(stdout);
}
return 0;
}