Commit | Line | Data |
---|---|---|
4efb3868 | 1 | /* |
2 | * misc.c: Miscellaneous helpful functions. | |
3 | */ | |
4 | ||
5 | #include <assert.h> | |
6 | #include <stdlib.h> | |
7 | ||
8 | #include "puzzles.h" | |
9 | ||
10 | int rand_upto(int limit) | |
11 | { | |
12 | unsigned long divisor = RAND_MAX / (unsigned)limit; | |
13 | unsigned long max = divisor * (unsigned)limit; | |
14 | unsigned long n; | |
15 | ||
16 | assert(limit > 0); | |
17 | ||
18 | do { | |
19 | n = rand(); | |
20 | } while (n >= max); | |
21 | ||
22 | n /= divisor; | |
23 | ||
24 | return (int)n; | |
25 | } |