4
I have a randomized number creation algorithm for lotteries that have the following characteristics:
1° The number to be generated must be reported.
2° Numbers cannot be repeated.
3° Numbers need to be in ascending order.
Since I’m a beginner in PHP, I tried to make "the algorithm work". For this, I created a class with a function geraNumeros()
recursively in order to make all these items and return me an array where I sort using the asort()
and then turn into string with implode()
. Is there any way to optimize it ?
<?php
class loterias{
public function geraNumero($aQuantidade, $aMinimo, $aMaximo) {
$contador = 0;
$result = array();
while ($aQuantidade):
$result[$aQuantidade] = str_pad(rand($aMinimo, $aMaximo), 2, '0', STR_PAD_LEFT);
$aQuantidade--;
$contador++;
endwhile;
while ($contador !== count(array_unique($result))):
$result = $this->geraNumero($contador, $aMinimo, $aMaximo);
endwhile;
return $result;
}
}
// Parametros //
$quantidade = 6;
$minimo = 1;
$maximo = 60;
$mega = new loterias();
$result = $mega->geraNumero($quantidade, $minimo, $maximo);
asort($result);
var_dump($result);
Do you have any specific complaints? It is certainly possible to optimize, but need?
– Maniero
to start, I wanted to leave all the treatment inside the generating function, using the asort($result) before the Return and in the Return use the Return implode(' - ',$result); to get out a string, It happens that when the one of the values of this array repeats and enters the second while and generates new non-repeating numbers, when it goes pro Return it goes back in the asort and picks up the repeated numbers. I didn’t understand why then I had to do the treatment outside the function, and I also find it slow...
– Gabriel Rodrigues
Another thing: it needs to be recursive?
– gmsantos
I couldn’t do without being recursive...
– Gabriel Rodrigues
Take a look at these questions, see if any serve: http://answall.com/search?q=fisher+yates - Fisher-Yates is suitable for lottery, you scramble the number set and take as many numbers as necessary.
– Bacco