Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

113
Views
Generate same random number based on string parameter

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
about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

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

about 4 years ago · Juan Pablo Isaza Report

0

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

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!