Skip to content

Instantly share code, notes, and snippets.

@chiro-hiro
Last active September 13, 2017 06:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save chiro-hiro/2a5c5a881bf6c33d02466b8d59eeaf07 to your computer and use it in GitHub Desktop.
Save chiro-hiro/2a5c5a881bf6c33d02466b8d59eeaf07 to your computer and use it in GitHub Desktop.
XorShift based PRNG
//Generate seed from Math.random()
var seed = Math.random()*Math.pow(2,32);

//XorShift based PRNG
function rnd(){
    var x = 0, i;
    for(i = 0; i < 32; i++){
        //Shift right if [i th] bit is equal to 1, otherwise shift letf
        x ^= ((seed >> i) & 1) ? seed >> i : seed << i;
    }
    return seed = x;
}

var a = [];
var c = 0;
for(var i = 0; i < 100; i++){
    c = (rnd() >>> 0);
    if(a.indexOf(c) < 0){
        a.push(c)
    }else{
        console.log(c);
    }
    
}

console.log(a.join(' '));

Result:

C:\Users\tad88\OneDrive\Documents\xorshift>node xorshitf.js
1589090782 3161481693 557693381 1942483294 1448329486 1443952414 1448822660
3364868321 553547413 3755325193 733098030 125019958 3138855523 142703684 282150964
441272032 3869994807 1529350573 1914626730 1309532900 2173482861 1444875502
4206194111 1146704225 1780325958 1230667686 432934580 4027225333 498978309 3189265479
191317473 3795657841 1183095747 419362340 2756529835 215393498 3099027097 924046116
2958600699 1298859023 1242357856 1853888256 617711078 1188259846 3839369693 1194380600
1672633550 3956858801 501852679 1534463996 770225648 2731411335 93621719 3131488453
2034461049 2967202271 1283033629 3597447005 759627798 4226088651 91861415 1083631060
2120242002 4256317381 1393827925 2304590541 203164801 4154652195 196999205 2770705095
1118087812 2514469165 1570611114 1386101704 1057343728 3090272609 2109513828 1914484406
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment