mrmo123
mrmo123

Reputation: 725

javascript non-sequential random number generator

does anyone know how to make a non-sequential random number generator in javascript? I know how to do a sequential one using Math.floor(Math.random()*11) where the number will fall in between 0-10. I'm looking for one that will only spit out 65, 83, 68, 70 (these numbers are the character codes for a, s, d, f...I'm making a keyboard game). The only other ones random number generators I've found are biased/non-uniform ones. If you could give me a general direction as to what this is called or even how to make on, it'd be greatly appreciated. Thanks so much!

Upvotes: 3

Views: 584

Answers (2)

Ignacio Vazquez-Abrams
Ignacio Vazquez-Abrams

Reputation: 798526

js> keymap = Array(65, 83, 68, 70);
[65, 83, 68, 70]
js> print(keymap[Math.floor(Math.random()*4)])
65
js> print(keymap[Math.floor(Math.random()*4)])
70
js> print(keymap[Math.floor(Math.random()*4)])
83
js> print(keymap[Math.floor(Math.random()*4)])
65

Upvotes: 2

Halcyon
Halcyon

Reputation: 57709

Map your codes and just use a consecutive index anyway:

var codes = [ 65, 83, 68, 70 ];
var index = Math.floor(Math.random()*codes.length);
var random_key = codes[index];  // tada!

Upvotes: 5

Related Questions