stackers - 5 months ago 36

Javascript Question

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

}

Recommended for you: Get network issues from **WhatsUp Gold**. **Not end users.**

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