2

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 ?

Anwar
  • 4,162
  • 4
  • 41
  • 62
  • Populate it with 1,2,3...9 and then [shuffle](http://stackoverflow.com/questions/2450954/how-to-randomize-shuffle-a-javascript-array?s=1|1.6991). – georg Nov 03 '14 at 16:38

4 Answers4

1

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.

Halcyon
  • 57,230
  • 10
  • 89
  • 128
1

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

Community
  • 1
  • 1
Alexandru Severin
  • 6,021
  • 11
  • 48
  • 71
1

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);
Quince
  • 14,790
  • 6
  • 60
  • 69
  • Thank you for your time, I understood your solution ! – Anwar Nov 03 '14 at 16:50
  • just realized i mis-read your question and made it so it has from min to max of the random numbers not 1-9, but ill leave it like this as it can easily be made to go from 1-9 by passing in 1 and 9 to `randomlyInitializeArray` – Quince Nov 03 '14 at 16:54
  • Yep, I just have to change your values, the algorithmic is clear for me thank you again :) – Anwar Nov 03 '14 at 17:01
0

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.

  • Thank you for answering Stick, however I prefer the shuffle() method because it is better suited for my needs. – Anwar Nov 03 '14 at 16:51