Can this help you?
function getRandomPin() {
return '0' + Math.floor(Math.random() * 900 + 100);
}
console.log(getRandomPin());
console.log(getRandomPin());
console.log(getRandomPin());
The bounds of this solution go from 0100
to 0999
Instead, for the following one, I added more controls about the numbers that can be generated under 0100
:
function getRandomPin() {
var temp = Math.floor(Math.random() * 1000);
if (temp < 100) {
if (temp < 10) {
return '000' + temp;
}
else {
return '00' + temp;
}
}
else {
return '0' + temp;
}
}
console.log(getRandomPin());
console.log(getRandomPin());
console.log(getRandomPin());
EDIT: The following is a solution that takes out a number that start with the 0
cipher if the previous outcome was not starting with that digit, as requested by comment:
var bool = false;
function getRandomPin() {
if (bool) {
var temp = Math.floor(Math.random() * 1000);
bool = false;
}
else {
var temp = Math.floor(Math.random() * 10000);
bool = true;
}
if (temp < 10) {
return '000' + temp;
}
else if (temp < 100) {
return '00' + temp;
}
else if (temp < 1000) {
return '0' + temp;
}
else {
return temp;
}
}
console.log(getRandomPin());
console.log(getRandomPin());
console.log(getRandomPin());
console.log(getRandomPin());
console.log(getRandomPin());
console.log(getRandomPin());
It's correct to advice that the last solution provides a number that start with 0
every time the previous number is at least 1000
, but this doesn't prevent a 0xyz
number after another 0xyz
one.