PHP RANDOM NUMBERS EXCLUDING A NUMBER FROM THE LIST

Asked

Viewed 269 times

-2

Good afternoon, I need for a school work do a search of 7 numbers from 1 to 20, excluding a number from the list.

Example: 7 Random numbers from 1 to 20, excluding the number 5 in the list. Return 7 numbers all different from 5.

function random($nNumeros, $nQuant) 
{ 
    $aRand = array(); 
    for ($i=1; $i<=$nQuant; $i++) { 
        $aRand[$i] = $rand = rand(1, 20) ; 
        while (count($aRand) < $nNumeros) 
            if (!in_array($rand, $aRand)) 
                $aRand[] = $rand; 
            else 
                $rand = rand(1, 20); 
    } 
    return $aRand; 
} 
echo "<pre>"; 
print_r(random(7,1)); //1
?>```
  • What exactly is $nQuant? Could you describe in text what your code is doing?

1 answer

0


There are several ways to do this, one would be by building a dictionary that ignores invalid ones and another would be by making a loop, discarding invalid ones.


I will do the first one, which follows the somewhat opposite logic of your current code. So for this you need to use the range to create the initial dictionary:

$dicionario = range(1, 20);

This will create an array with values from 1 to 20.


Then you need to delete the invalid values. So we can assume that the $excluidos is something like array(1, 2, 3) (that is: 1, 2 and 3 cannot be chosen). For this you can use the array_diff:

$dicionario = array_values(array_diff($dicionario, $excluidos));

The array_values is used to avoid "ranges" in the array.


Then you can generate a number from 0 to the maximum number in $dicionario, using random_int.


Then at the end you’ll have something like:

function Gerar(int $Quantidade, int $Maximo, array $Excluidos) : array {
    
    // Cria o array inicial
    $dicionario = range(1, $Maximo);
    
    // Exclui os inválidos
    $dicionario = array_values(array_diff($dicionario, $Excluidos));
    
    $resultado = [];
    
    // Gera a quantidade de número definidas
    for ($i = 0; $i < $Quantidade; $i++) {
        
        // Gera um número aletorio de 0 até a quantidade existente no dicionario.
        $id = random_int(0, count($dicionario) - 1);
        
        // Salva no "resultado"
        $resultado[] = $dicionario[$id];
        
        // Remove o número gerado da lista, afim de não gerar novamente o mesmo número
        unset($dicionario[$id]);
        $dicionario = array_values($dicionario);
        
    }
    
    return $resultado;  
}

Which can be used as:

// Gerar *7* numeros, de 1 até *20* e excluindo o *5*:
echo implode(",", Gerar(7, 20, [5]));
 

Upshot:

20,9,19,6,13,18,14

There are 7 numbers from 1 to 20, without repetition and without the 5.


Note that no verification has been added to the function, so generating more than the existing amount or deleting more than possible will not return clear errors, only PHP’s own Warning.

Browser other questions tagged

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