How to generate Mega-Sena results ignoring some numbers?

Asked

Viewed 1,995 times

6

I want to generate some games for Mega-Sena using Javascript, so I can ignore 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 modality where six numbers are drawn between 1 to 60 not being repeated.

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

  • 1

    You can try a function like Math.Random(); http://www.w3schools.com/jsref/jsref_random.asp or some other more advanced, like neural network, etc.

1 answer

10


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 checks if the number already exists in the series. I created another function chaveExistente() to check if the key has already left.

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

Browser other questions tagged

You are not signed in. Login or sign up in order to post.