Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generate random integer with ALL digits from 1-9

Tags:

javascript

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.

like image 598
chris97ong Avatar asked Mar 28 '14 08:03

chris97ong


People also ask

How do you generate a random number from 1 to 9 in Java?

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.

How do you generate a random number from 1 to 9 in Python?

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].

How do you generate a random number 1 9 C++?

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.


2 Answers

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("");
}
like image 119
ElmoVanKielmo Avatar answered Sep 20 '22 11:09

ElmoVanKielmo


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.

like image 24
thefourtheye Avatar answered Sep 21 '22 11:09

thefourtheye