I have this function to create a random 4 digit number:
generateCode = function(){
var fullNumber = [];
var digit1 = Math.floor(Math.random() * 9) + 1;
var digit2 = Math.floor(Math.random() * 9) + 1;
var digit3 = Math.floor(Math.random() * 9) + 1;
var digit4 = Math.floor(Math.random() * 9) + 1;
fullNumber.push(digit1, digit2, digit3, digit4);
this.theCode(fullNumber.join("")) ;
}
But I need to create a 4 digit random number with no repeating digits.
So "1234" or "9673". But not "1145" or "5668"
Is there an efficient way to do this?
You can use this handy shuffle
function to shuffle an array containing the numbers, and pick the first 4.
function random4Digit(){
return shuffle( "0123456789".split('') ).join('').substring(0,4);
}
function shuffle(o){
for(var j, x, i = o.length; i; j = Math.floor(Math.random() * i), x = o[--i], o[i] = o[j], o[j] = x);
return o;
}
alert( random4Digit() );
Edit: If you actually want a Number not starting with 0:
function random4DigitNumberNotStartingWithZero(){
// I did not include the zero, for the first digit
var digits = "123456789".split(''),
first = shuffle(digits).pop();
// Add "0" to the array
digits.push('0');
return parseInt( first + shuffle(digits).join('').substring(0,3), 10);
}
function shuffle(o){
for(var j, x, i = o.length; i; j = Math.floor(Math.random() * i), x = o[--i], o[i] = o[j], o[j] = x);
return o;
}
alert( random4DigitNumberNotStartingWithZero() );
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With