Home > Software engineering >  Generate random 6 characters based on input
Generate random 6 characters based on input

Time:10-10

Generate random 6 characters based on input. Like I want to turn 1028797107357892628 into j4w8p. Or 102879708974181177 into lg36k but I want it to be consistant. Like whenever I feed 1028797107357892628 in, it should always spit out j4w8p. Is this possible? (Without a database if possible.) I know how to generate random 6 characters but I dont know how to connect it with an input tbh. I would appreciate any help, thanks.

let rid = (Math.random()   1).toString(36).substring(7); 

CodePudding user response:

You can create a custom hashing function a simple function to your code would be

const seed = "1028797089741811773";

function customHash(str, outLen){
  //The 4 in the next regex needs to be the length of the seed divided by the desired hash lenght
  const regx = new RegExp(`.{1,${Math.floor(str.length / outLen)}}`, 'g')
  const splitted = str.match(regx);
  
 
  
  let out = "";
  for(const c of splitted){
    let ASCII = c % 126;
    if( ASCII < 33) ASCII = 33
  
   out  = String.fromCharCode(ASCII)
  }

  return out.slice(0, outLen)
}


const output = customHash(seed, 6)

console.log(output)

CodePudding user response:

It is called hashing, hashing is not random. In your example to get rid:

let rid = (Math.random()   1).toString(36).substring(7);

Because it is random, it's impossible to be able to produce "consistant result" as you expect.

You need algorithm to produce a "random" consistant result.

CodePudding user response:

Thanks everyone, solved my issue.

Code:

  let seed = Number(1028797089741811773)
  let rid = seed.toString(36).substring(0,6)
  console.log(rid)

  • Related