How can I create a random 16 digit number that doesn't previously exist in a list?
Let's say I have the following list:
const nums = [7856328870763265, 0107654389657487];
I need a function to generate random 16 digit numbers but that doesn't create duplicates.
I have the following:
const val = Math.floor(1000 Math.random() * 9000).toString();
const random16digitnumber = val val val val;
console.log(random16digitnumber);
console.log(typeof random16digitnumber);
But im afraid at some point it will start creating duplicates. I'm using the random16digitnumber as a primary key in a SQL database for a small school project.
So going back to my example, how can I create a random 16 digit number that doesn't previously exist in an array?
CodePudding user response:
I'll answer with an inline comment. I left your algo "as is". There might be reasons of why you're doing it this way; so I just implemented the logic you've wished for.
const nums = [7856328870763265, 0107654389657487];
const getNextRandomNumber = () => {
const val = Math.floor(1000 Math.random() * 9000).toString();
const candidate = val val val val;
// the generated number is part of the list;
// recursively call this function to generate another one
// (this works like a loop, just using call recursion)
// until a number is found that is not part of the list
// then the return below this if() is triggered
// and the "good" candidate is returned
if (nums[candidate]) {
return getNextRandomNumber();
}
// parseInt makes sure the string is converted back to number
// making sure we're using base 10, even if the first digit
// might be 0
return parseInt(candidate, 10);
}
// push() adds an element to the array
// the return value (100% guaranteed to be collision free random number)
// is added via the function call. The function logic makes sure
// it is absolutely unique
nums.push(getNextRandomNumber());