Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- console.log("With 500");
- console.log(randomNumber(500));
- console.log("With 1");
- console.log(randomNumber(1));
- console.log("With 500");
- console.log(randomNumber(500));
- console.log("With 1000001");
- console.log(randomNumber(1000001));
- /*
- Some tests
- With 500
- 19
- With 1
- 1
- With 500
- 31
- With 1000001
- Number bigger than expected.
- undefined
- With 500
- 169
- With 1
- 0
- With 500
- 273
- With 1000001
- Number bigger than expected.
- undefined
- */
- function flip() {
- return Math.random() >= 0.5;
- }
- /**
- * This function uses a modified version of the Middle Square Weyl Sequence PRNG algorithm
- *
- * @param {*} max Max number in the iterval
- * @param {*} min Min number in the interval (for this test will be always 0)
- */
- function msws(max, min) {
- var clamped = !!max; // returns a Boolean value (true or false) depending on the truthiness of the expression.
- var done = false;
- var i = 0;
- var x = 0;
- var w = 0;
- var j = 0;
- // To give it a feeling of more randomness I'm adding these few lines with the use of flip()
- var primes = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97];
- // First select a seed based on the result of flip
- if(flip()){
- s = 0x45ad4e1ce2ace;
- } else {
- s = 0x165ad49659;
- }
- // Add these three call to flip() to have more randomness in the seed, in each iteration the seed will change using the first 25
- // numbers
- while(flip() && flip() || flip()){
- s *= primes[j];
- j++;
- if(j === 5){
- j = 0;
- }
- }
- if(max > 1000000 || max < 0){
- console.log("Number bigger than expected.");
- return;
- }
- while (!done) {
- i += 1;
- x *= x;
- x += (w += s);
- x = (x >> 16) | (x << 16);
- x = (x < 0) ? x * -1 : x;
- var outOfBounds = clamped && ((x > max) || (min && x < min));
- if (!clamped) {
- done = true;
- } else if (!outOfBounds) {
- done = true;
- }
- }
- return x;
- }
- function randomNumber(max) {
- return msws(max, 0);
- }
Add Comment
Please, Sign In to add comment