0

I'm trying to make array of seven random numbers so far this is my code:

function lotoGenerator() {
        var array = [];
        var i;
    for (i = 0; i <=6; i++) {
        var temp = Math.floor((Math.random() * 39) + 1);
        array.push(temp);
    }    
    console.log(array);
}
lotoGenerator();

Now with this code I can get results like this [30, 6, 36, 8, 16, 27, 6]. As you can see number 6 come out two times. Is there a way to make array not repeat numbers. I'm new to javaScript and I wasn't able to implement solutions I found online.

Karadjordje
  • 315
  • 3
  • 13

3 Answers3

7

Place a do ... while statement on your random generation that check if the number was already on the loto numbers.

function lotoGenerator() {
        var array = [];
        var i;
    for (i = 0; i <=6; i++) {
        do {
            // Generate your random number
            var temp = Math.floor((Math.random() * 39) + 1);
            // If the number already exists, the index of it on loto array will be different of -1, so it already exists
            var alreadyExists = array.indexOf(temp) !== -1;
        } while (alreadyExists) // Repeat this many times necessary to get an unique number.

        array.push(temp);
    }    
    console.log(array);
}
lotoGenerator();

Note that this isn't the most efficient solution since you can have the bad luck of having the same number sorted many times, so the do...while loop may run too many times.

The best way to solve this is by having an array with available numbers and removing the drawn number:

function lotoGenerator() {
    var available = [];
    var drawn = [];
    for (var i = 1; i<= 40; i++) {
        available.push(i);
    }

    for (i = 0; i <=6; i++) {
        var random = Math.floor((Math.random() * available.length));
        drawn.push(available[random]);
        available.splice(random, 1);
    }

    return drawn;
}

This second function have an well known execution time, and will be more efficient as the number of random elements increase.

Elias Soares
  • 9,884
  • 4
  • 29
  • 59
3

This is one of the options:

function lotoGenerator() {
    var array = [], i = 0, temp;
    while (i <= 6) {
        temp = Math.floor((Math.random() * 39) + 1);
        if ( array.indexOf(temp) > -1 ) continue;
        i = array.push(temp);
    }    
    console.log(array);
}
Ram
  • 143,282
  • 16
  • 168
  • 197
1

Adding if(array.indexOf(temp) > -1) continue; will do the trick to your code.

function lotoGenerator() {
        var array = [];
    while (array.length <= 6) {
        var temp = Math.floor((Math.random() * 39) + 1);
        if(array.indexOf(temp) > -1) continue;
        array.push(temp);
    }    
    console.log(array);
}
lotoGenerator();
Mr.7
  • 2,292
  • 1
  • 20
  • 33