First I think it's better to split this into several functions, a function as the name suggests should do a single function.
In the meantime you can simply use count()
with array_unique()
and using sort()
to keep same order, because of performance this is not ideal, however it is simple to understand the concept.
function removerDuplicidade(array $array)
{
sort($array);
return array_unique($array, SORT_REGULAR);
}
function criarAposta(int $quantidadeDeDezenasParaMarcar, int $numeroMaximoDisponivelNaCartela)
{
$aposta = [];
while (count($aposta) < $quantidadeDeDezenasParaMarcar) {
$aposta[] = random_int(0, $numeroMaximoDisponivelNaCartela);
$aposta = removerDuplicidade($aposta);
}
return $aposta;
}
The idea is simple, every number generated by random_int
, requires PHP 7 , will be "filtered" by removerDuplicidade
, it is responsible for keeping the order increasing (due to sort()
) and will remove duplicates due to array_unique()
.
Assuming it manages three numbers:
$aposta = [1, 10, 20];
Suppose it manages 10
, which already exists, this number will be removed by array_unique
. Since while
is set by count()
the count will remain 3
, once the fourth number has been removed.
In the meantime, you need to generate more than one, so you can use a new function, similar to as a plugin :
function criarMultiplasApostas(int $quantidadeDeApostas, int $quantidadeDeDezenas, int $numeroMaximoDisponivelNaCartela)
{
$multiplasApostas = [];
while (count($multiplasApostas) < $quantidadeDeApostas) {
$multiplasApostas[] = criarAposta($quantidadeDeDezenas, $numeroMaximoDisponivelNaCartela);
$multiplasApostas = removerDuplicidade($multiplasApostas);
}
return $multiplasApostas;
}
This will cause you to run multiple bets, assuming you manage two:
$multiplasApostas = [
[1,2,3,4,5,6]
[1,2,3,4,5,6]
];
This would be removed by removerDuplicidade
because they are identical bets, so sort
is used so that they are always in the same order and therefore removed.
/! \ Failures
One of the flaws is that you might try:
gerarMultiplasApostas(100, 6, 7);
This is to generate 100 bets with 6 numbers each in a space of 8 numbers (0,1,2,3,4,5,6,7,8). This is mathematically impossible, the calculation of combinations is exactly:
8! / (6! * (8 - 6)!)
As soon as there are only 28
combinations, set 100
will create an infinite loop, which would even be possible a DoS, because each process would be locked for 30 seconds, by default.
Another failure is that removerDuplicidade
will not work out of order, with sort
being extremely necessary to generate the bets.