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.
Java Random number between 1 and 10 Below is the code showing how to generate a random number between 1 and 10 inclusive. Random random = new Random(); int rand = 0; while (true){ rand = random. nextInt(11); if(rand != 0) break; } System.
Use a random.randint() function to get a random integer number from the inclusive range. For example, random.randint(0, 10) will return a random number from [0, 1, 2, 3, 4, 5, 6, 7, 8 ,9, 10].
One way to generate these numbers in C++ is to use the function rand(). Rand is defined as: #include <cstdlib> int rand(); The rand function takes no arguments and returns an integer that is a pseudo-random number between 0 and RAND_MAX.
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("");
}
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.
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