简体   繁体   中英

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!

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!
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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM