Anwar
Anwar

Reputation: 4246

populate array with UNIQUE random numbers javascript

I have an array :

var array = new Array();

Here is the random function, which gives a random number between min and max (seen in a previous Stackoverflow topic) :

function randomIntFromInterval(min,max) {
    return Math.floor(Math.random()*(max-min+1)+min);
}

This array is meant to have 9 cells. I would like to populate it with random number, with the important condition that each of those number are unique, which means a number in this array cannot be found twice or more.So finally, here is where I am stuck (whole code) :

var array = new Array();

function randomIntFromInterval(min,max) {
    return Math.floor(Math.random()*(max-min+1)+min);
}

// populate the variable "array" with 9 different
// random numbers
function randomlyInitializeArray() {
    var random = 0;

    // For each cell (9 cells) in my "array"
    for (var i = 0; i < maxLength; i++) {

        // Return a number between 1 & 9
        random = randomIntFromInterval(1, maxLength);

        /*  Verifying if this random number is already in 
            the "array" /!\ stuck here /!\ */
    }
}

So, what is the logic for populate an array with 9 unique (different) number ?

Upvotes: 2

Views: 3330

Answers (4)

Halcyon
Halcyon

Reputation: 57729

So you want 9 random unique numbers from 1-9? That seems to me the same as wanting the numbers 1 to 9 in a random order.

This can be done simply with:

[1,2,3,4,5,6,7,8,9].sort(function () { // shuffle
    return Math.random() - 0.5; // returns > 0 ~50% of the time
});

Otherwise you could do something like:

var array = [];
while (array.length < 9) {
    array = array_unique(array.concat([ get_random_number() ]);
}
console.log(array);

Most frameworks have an array_unique function in one way or another, or just write your own.

There are faster ways to do this but the explicit inclusion of the call to unique() makes this implementation easy to understand and verify.

Upvotes: 1

Quince
Quince

Reputation: 14990

why not get an array from 1 to - max then shuffle it

//+ Jonas Raoni Soares Silva
//@ http://jsfromhell.com/array/shuffle [v1.0]

function shuffle(o) { //v1.0
  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;
};

function randomIntFromInterval(min, max) {
  return Math.floor(Math.random() * (max - min + 1) + min);
}

// populate the variable "array" with 9 different
// random numbers
function randomlyInitializeArray(min, max) {
  var start = min;
  var randomMax = randomIntFromInterval(min, max)
  var myArray = [];
  for (var i = 0; start <= randomMax; myArray[i++] = start++);

  myArray = shuffle(myArray);
  console.log("Min: "+min);
  console.log("Max: "+max);
  console.log("random Max: "+randomMax)
  
  console.log(myArray)

}

randomlyInitializeArray(2,40);

Upvotes: 1

Alexandru Severin
Alexandru Severin

Reputation: 6228

If you want to get 9 random numbers from a specific interval(using that function):

You could use a do-while loop to get random numbers until you have an unique one.

You can check if a number is already in an array via contains() function.

for (var i = 0; i < maxLength; i++) {
    do {
        random = randomIntFromInterval(1, maxLength);
    while( array.contains(random) );          // will return false if random isn't asigned

    array.push(random);
}

If you do not care about the interval, and you just want 9 unique values (1-9 in a random order) you can create the array with 1-9 and shuffle it with:

var myArray = ['1','2','3','4','5','6','7','8','9'];
newArray = shuffle(myArray);

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;
};

shuffle method taken from how can I shuffle an array

Upvotes: 1

user890167
user890167

Reputation:

I'd recommend a while loop, something like

function unique_nums(n) {
    var myarray = [];
    for (var i=0;i<n;i++){
        var next_num = Math.random();
        while (myarray.indexOf(next_num) !== -1) {
            next_num = Math.random();
        }
        myarray.push(next_num);
    }
    return myarray;
}

This will ensure that the random number doesn't exist within the array before it is pushed.

Upvotes: 0

Related Questions