forked from SkienaBooks/Algorithm-Design-Manual-Programs
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrandom.c
92 lines (68 loc) · 2.15 KB
/
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
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
/*
random.c
Compute random numbers within given ranges
by: Steven Skiena
*/
/*
Copyright 2003 by Steven S. Skiena; all rights reserved.
Permission is granted for use in non-commerical applications
provided this copyright notice remains intact and unchanged.
This program appears in my book:
"Programming Challenges: The Programming Contest Training Manual"
by Steven Skiena and Miguel Revilla, Springer-Verlag, New York 2003.
See our website www.programming-challenges.com for additional information.
This book can be ordered from Amazon.com at
http://www.amazon.com/exec/obidos/ASIN/0387001638/thealgorithmrepo/
*/
#include <math.h>
#include <stdio.h>
#include <stdlib.h>
#include "random.h"
/**************************************************************************/
/* These functions generate random numbers in the designated ranges */
void swap(int *a, int *b) {
int x;
x = *a;
*a = *b;
*b = x;
}
int random_int(int low, int high) { /* lower/upper bounds on numb*/
int rand();
int i, j, r; /* random number*/
i = RAND_MAX / (high - low + 1);
i *= (high - low + 1);
while ((j = rand()) >= i) {
continue;
}
r = (j % (high - low + 1)) + low;
if ((r < low) || (r > high)) {
printf("Error: random integer %d out of range [%d,%d]\n",
r, low, high);
}
return(r);
}
/* Construct a random permutation of the $n$ elements of the
given array.
*/
void random_permutation(int a[], int n) {
int i;
for (i=n; i>1; i--) {
swap(&a[i - 1], &a[random_int(0, i - 1)]);
}
}
double random_float(int low, int high) { /*lower/upper bounds on numb*/
int rand();
double i, j; /* avoid arithmetic trouble */
double r; /* random number*/
i = RAND_MAX / (high - low);
i *= (high - low);
while ((j = rand()) >= i) {
continue;
}
r = (j / i) * (high - low) + low;
if ((r < low) || (r > high)) {
printf("ERROR: random real %f out of range [%d,%d]\n",
r, low, high);
}
return(r);
}