Seedable JavaScript random number generator

前端 未结 9 805
暖寄归人
暖寄归人 2020-11-22 10:13

The JavaScript Math.random() function returns a random value between 0 and 1, automatically seeded based on the current time (similar to Java I believe). However, I don\'t

9条回答
  •  遥遥无期
    2020-11-22 10:41

    Note: This code was originally included in the question above. In the interests of keeping the question short and focused, I've moved it to this Community Wiki answer.

    I found this code kicking around and it appears to work fine for getting a random number and then using the seed afterward but I'm not quite sure how the logic works (e.g. where the 2345678901, 48271 & 2147483647 numbers came from).

    function nextRandomNumber(){
      var hi = this.seed / this.Q;
      var lo = this.seed % this.Q;
      var test = this.A * lo - this.R * hi;
      if(test > 0){
        this.seed = test;
      } else {
        this.seed = test + this.M;
      }
      return (this.seed * this.oneOverM);
    }
    
    function RandomNumberGenerator(){
      var d = new Date();
      this.seed = 2345678901 + (d.getSeconds() * 0xFFFFFF) + (d.getMinutes() * 0xFFFF);
      this.A = 48271;
      this.M = 2147483647;
      this.Q = this.M / this.A;
      this.R = this.M % this.A;
      this.oneOverM = 1.0 / this.M;
      this.next = nextRandomNumber;
      return this;
    }
    
    function createRandomNumber(Min, Max){
      var rand = new RandomNumberGenerator();
      return Math.round((Max-Min) * rand.next() + Min);
    }
    
    //Thus I can now do:
    var letters = ['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z'];
    var numbers = ['1','2','3','4','5','6','7','8','9','10'];
    var colors = ['red','orange','yellow','green','blue','indigo','violet'];
    var first = letters[createRandomNumber(0, letters.length)];
    var second = numbers[createRandomNumber(0, numbers.length)];
    var third = colors[createRandomNumber(0, colors.length)];
    
    alert("Today's show was brought to you by the letter: " + first + ", the number " + second + ", and the color " + third + "!");
    
    /*
      If I could pass my own seed into the createRandomNumber(min, max, seed);
      function then I could reproduce a random output later if desired.
    */
    

提交回复
热议问题