-2

I want to make an algorithm, for a NodeJS app, that converta any given string to a 1 to 3 digit number (better if the number is between 1-500).

e.g
ExampleString -> 214

Can anyone help me find a good solution?

EDIT: I want to get a crime coefficient number from a username (string).

2 Answers2

0

Ok, you can use JS function to get charCode of letter

let str = "some string example";
let sum = 0;
for (let i=0; i<str.length; i++) {
  sum += parseInt(str[i].charCodeAt(0), 10); // Sum all codes
}

// Now we have some value as Number in sum, lets convert it to 0..1 value to scale to needed value
let rangedSum = parseFloat('0.' + String(sum)); // Looks dirty but works
let resultValue = Math.round(rangedSum * 500) + 1; // Same alogorythm as using Math.random(Math.round() * (max-min)) + min;

I hope it helps.

So as you are using nodejs, you can use crypto library to get md5 hash of string and then get it as HEX.

const crypto = require('crypto');
let valueHex = crypto.createHash('md5').update('YOUR STRING HERE').digest('hex');
// then get it as decimal based value
let valueDec = parseInt(valueHex, 16);
// and apply the same algorythm as above to scale it between 1-500
P1ratRuleZZZ
  • 144
  • 2
  • 7
0

function coeficient() {
  return Math.floor(Math.random() * 500) + 1;
}

console.log(coeficient());
console.log(coeficient());
console.log(coeficient());
ibrahim mahrir
  • 31,174
  • 5
  • 48
  • 73