-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathRandom.jack
66 lines (55 loc) · 1.82 KB
/
Random.jack
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
// Copyright (c) 2018, Bill Mei
// Pseudorandom number generator
// Uses the LCG Algorithm:
// https://en.wikipedia.org/wiki/Linear_congruential_generator
class Random {
static int lastInt;
function void init() {
do Random.generateSeed();
return;
}
// Use keyboard presses as noise to seed the Random Number Generator
function void generateSeed() {
var char key;
var boolean done;
var int randomnessCounter, seed;
let done = false;
do Strings.displayRandomInstructions();
while (~done) {
// Keydown
while (key = 0) {
let key = Keyboard.keyPressed();
}
do Output.moveCursor(6, 12);
do Output.printInt(randomnessCounter);
do Output.printChar(37); // %
let randomnessCounter = Math.min(randomnessCounter + 3, 100);
// Add the key to the seed
let seed = seed + Maths.charToInt(key);
if (key = 128) { let done = true; } // [enter] key to exit
// Keyup
while (~(key = 0)) {
let key = Keyboard.keyPressed();
}
}
// Initialize the lastInt with the seed.
let lastInt = seed;
do Screen.clearScreen();
do Output.moveCursor(0, 0);
do Strings.disposeRandomInstructions();
return;
}
// Next random integer created by the LCG.
function int next() {
// modulus = 32767 (max 16-bit signed int)
// multiplier = 7907 (arbitrary prime number)
// increment = 17 (arbitrary coprime number)
let lastInt = Maths.mod((lastInt * 17) + 7907, 32767);
return lastInt;
}
// Return a random integer between the
// lower (inclusive) and upper (exclusive) ranges.
function int randInt(int lower, int upper) {
return Maths.mod(Math.abs(Random.next()), upper - lower) + lower;
}
}