Javascript repeatable random number based on multi

2019-05-27 03:27发布

问题:

I am trying to create a function that takes 4 parameters and spits out a random number. But I want it so if the same 4 parameters are input, you will always get the same answer. The number should be between 0 and the max argument.

function random (x,y,z,max) {
    output = ;
    return Math.floor(output * max); 
}

Is there any simple forumala I can use to get this? I tried to create one but it didn't look random at all, and would look very similar if you changed one parameter very slightly. I want it to be completely different, but repeatable.

hash function:

function hash (input){
    input = 'random'+input;
    var hash = 0;
    if (input.length == 0) return hash;
    for (i = 0; i < input.length; i++) {
        char = input.charCodeAt(i);
        hash = ((hash<<5)-hash)+char;
        hash = hash & hash; // Convert to 32bit integer
    }
    return Math.abs(hash);
}

回答1:

Generating an apparently unpredictable data from another is called "hashing"; restricting it to a range is called "modulo". Here is an easy way to do hashing using exponentiation:

const hashLim = () => {
  const args = Array.prototype.slice.call(arguments);
  const limit = args.shift();
  var seed = limit - 1;
  
  for (a in args) {
    seed = Math.pow(args[a] + limit, seed) % limit
  }
  return seed;
}

document.write(hashLim(100, 4, 16, 64) + '<br/>')
document.write(hashLim(100, 5, 16, 64))



回答2:

You can use some self made calculation for pseudo random values, like this example with pi and the taking of only the fractal part.

function Random(seed) {            
    var r = seed;
    this.random = function () {
        var v = r * Math.PI;
        r = v - (v | 0);
        return r;
    }
    this.random();
}

var i,
    q = new Random(42),
    r = new Random(42);
for (i = 0; i < 10; i++) {
    document.write(q.random() +'<br>'+ r.random() + '<hr>');
}