Created
November 3, 2014 20:12
-
-
Save ybakos/7ca67fcfd07477a9550b to your computer and use it in GitHub Desktop.
Jack Pseudo Random Numbers for Nand 2 Tetris
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* Random.jack | |
* By Mark Armbrust | |
* http://nand2tetris-questions-and-answers-forum.32033.n3.nabble.com/Random-number-generator-for-hack-cpu-td4025503.html | |
* Also see: | |
* http://nand2tetris-questions-and-answers-forum.32033.n3.nabble.com/Pseudo-Random-Number-Generator-td4026059.html#a4027617 | |
*/ | |
class Random { | |
static int seed; | |
function void setSeed(int newSeed) { | |
let seed = newSeed; | |
return; | |
} | |
function int rand() { | |
/** return a random number in the range 0..32767 */ | |
let seed = seed + 20251; | |
if (seed < 0) { | |
let seed = seed - 32767 - 1; | |
} | |
return seed; | |
} | |
function int randRange(int range) { | |
/** return a random number in the range 0..range */ | |
var int mask; | |
var int ret; | |
let mask = 1; | |
while (mask < range) { | |
let mask = mask * 2 + 1; | |
} | |
let ret = Random.rand() & mask; | |
while (ret > range) { | |
let ret = Random.rand() & mask; | |
} | |
return ret; | |
} | |
} |
Thanks for this! very helpful.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This random module was very useful