How to generate Mega-Sena results by ignoring some numbers?

6

I want to generate some games for Mega-Sena using JavaScript, so that I can skip a list of numbers and indicate the total number of games to be generated. Knowing that each game will have 6 numbers, what is the best way to generate these games?

var numeros_ignorados = [];
var quantidade_de_jogos;
// operação para gerar jogos

* Mega-Sena is a lottery mode where six numbers are drawn from 1 to 60 not being repeated.

The numeros_ignorados are individual numbers that should not appear in any series. For example, 13 and 10 .

    
asked by anonymous 22.11.2014 / 17:31

1 answer

7

Here's a suggestion:

var numeros_ignorados = [13, 10];
var quantidade_de_jogos = 3; // pode mudar a quantidade aqui
var jogos = [];

function gerarNumero(existentes) {
    var novoNumero = parseInt(Math.random() * 59, 10) + 1;
    if (existentes.indexOf(novoNumero) != -1 || numeros_ignorados.indexOf(novoNumero) != -1) novoNumero = gerarNumero(existentes);
    return novoNumero;
}

function chaveExistente(chave) {
    var chaves = jogos.map(function (chv) {
        return chv.join();
    });
    return chaves.indexOf(chave.join()) != -1;
}

for (var i = 0; i < quantidade_de_jogos; i++) {
    var numeros = [];
    while (numeros.length < 6) {
        numeros.push(gerarNumero(numeros));
    }
    numeros = numeros.sort();
    chaveExistente(numeros) ? quantidade_de_jogos++ : jogos.push(numeros);
}
alert(JSON.stringify(jogos, null, 4));

I created a function to generate numbers that also verifies if the number already exists in the series. I created another function chaveExistente() to check if the key has already exited.

This code generates an array of arrays. An example is:

[
    [14, 21, 24, 32, 44, 50],
    [16, 33, 36, 37, 4, 44],
    [11, 2, 24, 34, 4, 45]
]
    
22.11.2014 / 18:24