I'm trying to create a function that will generate the same random number on each execution if the string is the same.
function generateRandom(maxInt, stringParam) {
//generate random based on stringParam
//output int number from 0 to maxInt
}
The goal is to generate the same random number (on different pages) if the stringKey is the same.
generateRandom(100, 'abc') // 73
generateRandom(100, 'abc') // 73
generateRandom(100, 'abc') // 73
generateRandom(100, 'qwe') // 45
generateRandom(100, 'qwe') // 45
generateRandom(100, 'qwe') // 45
CodePudding user response:
This isn't really random. I would say this is a kind of encryption. Hopefully, it works for your requirement.
First, get the Unicode from each character in the string. Sum them up and then use %
(Remainer operator) to round the number to be within MaxInt
range. This will result in the same number every time you input the same maxInt
and the same stringParam
.
function generateRandom(maxInt, stringParam) {
let sum = 0;
for (let i = 0; i < stringParam.length; i ){
sum = stringParam.charCodeAt(i);
}
let result = sum % maxInt;
console.log(result);
return result;
}
generateRandom(100, 'abc')
generateRandom(100, 'abc')
generateRandom(100, 'abc')
generateRandom(100, 'qwe')
generateRandom(100, 'qwe')
generateRandom(100, 'qwe')
CodePudding user response:
I'd suggest using a hashing function
for this purpose, perhaps a simple one in this case.
Once we have the hash we'll mod with our max output value, e.g. hash % maxInt.
This will give the same output for a given input.
// Simple implementation of a string hashing function (Bernstein)
function hashCode(input) {
return [...input].reduce((hash, chr) => {
return hash * 33 chr.charCodeAt(0);
}, 0);
}
function generateRandom(maxInt, stringParam) {
return hashCode(stringParam) % maxInt;
}
const maxInt = 100;
const inputs = [ 'qwe', 'qwe', 'abc', 'abc', 'def', 'def'];
console.log('In ', 'Out')
inputs.forEach(input => console.log(input, generateRandom(maxInt, input)));
.as-console-wrapper { max-height: 100% !important; }