I have a algorithm for creating random numbers for lottery that have the following characteristics:
1 ° You must be informed of the number of numbers to be generated.
2 ° Numbers can not be repeated.
3 ° The numbers need to be in ascending order.
As a beginner in PHP, I tried to make the algorithm work. To do this, I created a class with a geraNumeros()
function recursively in order to do all these items and return an array where I sort using asort()
and then transform 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);