stackers stackers - 9 months ago 53
Javascript Question

Javascript repeatable random number based on multiple inputs

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);

Answer Source

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 =;
  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))

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download