44 lines
956 B
Text
44 lines
956 B
Text
seed = 1 /* seed of the random number generator */
|
|
scale = 0
|
|
|
|
/* Random number from 0 to 32767. */
|
|
define rand() {
|
|
/* Formula (from POSIX) for random numbers of low quality. */
|
|
seed = (seed * 1103515245 + 12345) % 4294967296
|
|
return ((seed / 65536) % 32768)
|
|
}
|
|
|
|
/* Shuffle the first _count_ elements of shuffle[]. */
|
|
define shuffle(count) {
|
|
auto b, i, j, t
|
|
|
|
i = count
|
|
while (i > 0) {
|
|
/* j = random number in [0, i) */
|
|
b = 32768 % i /* want rand() >= b */
|
|
while (1) {
|
|
j = rand()
|
|
if (j >= b) break
|
|
}
|
|
j = j % i
|
|
|
|
/* decrement i, swap shuffle[i] and shuffle[j] */
|
|
t = shuffle[--i]
|
|
shuffle[i] = shuffle[j]
|
|
shuffle[j] = t
|
|
}
|
|
}
|
|
|
|
/* Test program. */
|
|
define print_array(count) {
|
|
auto i
|
|
for (i = 0; i < count - 1; i++) print shuffle[i], ", "
|
|
print shuffle[i], "\n"
|
|
}
|
|
|
|
for (i = 0; i < 10; i++) shuffle[i] = 11 * (i + 1)
|
|
"Original array: "; trash = print_array(10)
|
|
|
|
trash = shuffle(10)
|
|
"Shuffled array: "; trash = print_array(10)
|
|
quit
|