-
Notifications
You must be signed in to change notification settings - Fork 0
/
gennumber.c
38 lines (32 loc) · 1003 Bytes
/
gennumber.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
#include <stdlib.h> // for drand48()
#include "gennumber.h"
#define ITER 10000
/* This is a helper function used only in this file.
This shuffles the array of ten characters pointed
by the parameter '*str.' */
void
shuffle(unsigned char *str) {
unsigned char p, q, tmp;
unsigned int i;
/* Swap the characters located at 'p' and 'q' ITER times. */
for (i = 0; i < ITER; i++) {
p = (unsigned char)(drand48()*10);
q = (unsigned char)(drand48()*10);
tmp = str[p];
str[p] = str[q];
str[q] = tmp;
}
}
/* This function makes a four-digit number,
which has different numbers in each digit. */
unsigned int
gennumber() {
unsigned char str[] = "0123456789";
unsigned int d;
shuffle(str);
/* 'str[x]' has the value of the character code of '0' to '9.'
Therefore, subtracting the character code of '0' from 'str[x]'
results in the numerical value from 0 to 9. */
d = (str[0]-'0')*1000+(str[1]-'0')*100+(str[2]-'0')*10+(str[3]-'0');
return d;
}