Guest User

Untitled

a guest
Nov 22nd, 2017
88
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.91 KB | None | 0 0
  1. console.log("With 500");
  2. console.log(randomNumber(500));
  3. console.log("With 1");
  4. console.log(randomNumber(1));
  5. console.log("With 500");
  6. console.log(randomNumber(500));
  7. console.log("With 1000001");
  8. console.log(randomNumber(1000001));
  9.  
  10. /*
  11.  
  12. Some tests
  13.  
  14. With 500
  15. 19
  16. With 1
  17. 1
  18. With 500
  19. 31
  20. With 1000001
  21. Number bigger than expected.
  22. undefined
  23.  
  24. With 500
  25. 169
  26. With 1
  27. 0
  28. With 500
  29. 273
  30. With 1000001
  31. Number bigger than expected.
  32. undefined
  33.  
  34. */
  35.  
  36. function flip() {
  37. return Math.random() >= 0.5;
  38. }
  39.  
  40. /**
  41. * This function uses a modified version of the Middle Square Weyl Sequence PRNG algorithm
  42. *
  43. * @param {*} max Max number in the iterval
  44. * @param {*} min Min number in the interval (for this test will be always 0)
  45. */
  46. function msws(max, min) {
  47. var clamped = !!max; // returns a Boolean value (true or false) depending on the truthiness of the expression.
  48. var done = false;
  49. var i = 0;
  50. var x = 0;
  51. var w = 0;
  52. var j = 0;
  53. // To give it a feeling of more randomness I'm adding these few lines with the use of flip()
  54. 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];
  55. // First select a seed based on the result of flip
  56. if(flip()){
  57. s = 0x45ad4e1ce2ace;
  58. } else {
  59. s = 0x165ad49659;
  60. }
  61. // Add these three call to flip() to have more randomness in the seed, in each iteration the seed will change using the first 25
  62. // numbers
  63. while(flip() && flip() || flip()){
  64. s *= primes[j];
  65. j++;
  66. if(j === 5){
  67. j = 0;
  68. }
  69. }
  70. if(max > 1000000 || max < 0){
  71. console.log("Number bigger than expected.");
  72. return;
  73. }
  74. while (!done) {
  75. i += 1;
  76. x *= x;
  77. x += (w += s);
  78. x = (x >> 16) | (x << 16);
  79. x = (x < 0) ? x * -1 : x;
  80. var outOfBounds = clamped && ((x > max) || (min && x < min));
  81. if (!clamped) {
  82. done = true;
  83. } else if (!outOfBounds) {
  84. done = true;
  85. }
  86. }
  87. return x;
  88. }
  89.  
  90. function randomNumber(max) {
  91. return msws(max, 0);
  92. }
Add Comment
Please, Sign In to add comment