Reputation: 7060
How do I generate a 9-digit integer that has all digits from 1-9? Like 123456798, 981234765, 342165978, etc.
Doing this:
var min = 100000000;
var max = 999999999;
var num = Math.floor(Math.random() * (max - min + 1)) + min;
does not work give me the integer that I want most of the time (does not have ALL digits from 1 to 9).
111111119 is not acceptable because each number must have at least one "1" in it, "2", "3", ... and a "9" in it.
Upvotes: 7
Views: 1304
Reputation: 11290
Just start with the string 123456789
and shuffle it randomly as described in How do I shuffle the characters in a string in JavaScript?
String.prototype.shuffle = function () {
var a = this.split(""),
n = a.length;
for(var i = n - 1; i > 0; i--) {
var j = Math.floor(Math.random() * (i + 1));
var tmp = a[i];
a[i] = a[j];
a[j] = tmp;
}
return a.join("");
}
Upvotes: 11
Reputation: 239463
This program, with little tweaks, will be a good addition to your custom utility belt.
Adapted from the _.shuffle
function of Underscore.js library, which shuffles the list of data with Fisher-Yates Shuffle algorithm.
function getRandomNumber() {
var rand, index = 0, shuffled = [1, 2, 3, 4, 5, 6, 7, 8, 9];
shuffled.forEach(function(value) {
rand = Math.floor(Math.random() * ++index);
shuffled[index - 1] = shuffled[rand];
shuffled[rand] = value;
});
return shuffled.reduce(function(result, current) {
return result * 10 + current;
}, 0);
}
console.log(getRandomNumber());
This program will always return a number which has all the 9 numbers in it and the length is also 9.
Upvotes: 4
Reputation: 2996
Recurse!
var randomize = function (str) {
if (str.length == 9) return str;
var newDigit = Math.floor(Math.random()*9 + 1);
if (str.indexOf(newDigit) == -1) {
return randomize(str + newDigit);
} else {
return randomize(str);
}
}
There's a lot of room for optimisation there. Or just use a simple loop.
Upvotes: 1