How to detect 3 equal numbers?

3

I have a For loop that has two mt_rand , one of random numbers and another mt_rand of numbers that are designated as prizes.

What I want to do now is check out 3 equal numbers, make the sum of the values that came out in this mt_rand of the 3 numbers and return in a variable with the sum of these values.

PHP

for ($i = 0; $i<9; $i++){
    $numeros = mt_rand(1,9);
    $premio = mt_rand(1,20);
    echo "valor" . ($i + 1) . "=$numeros&premio" . ($i + 1) . "=$premio&";
}
    
asked by anonymous 11.01.2017 / 11:25

2 answers

2

The question lacks more precise information to demonstrate a concise solution. But regardless of that, based on what you posted:

$premio_soma = 0;
for ($i = 0; $i<9; $i++) {
    $n = mt_rand(1, 9);
    $premio[$n][] = mt_rand(1, 20);
    if (isset($numeros[$n])) {
        $numeros[$n]++;
        // encontrou 3 ocorrências do mesmo número
        if ($numeros[$n] == 3) {
            // teste, exibe os 3 números a somar
            echo '<pre>'; print_r($premio[$n]); echo '</pre>'; //exit;
            // some os 3 numeros
            $premio_soma = array_sum($premio[$n]);
            // interrompe o laço de repetição
            break;
        }
    } else {
        $numeros[$n] = 1;
    }
}

echo 'premio: '.$premio_soma;

You can optimize and / or create better logic. I just did it in a way by following the logic of what I posted based on the "structure" of the original code.

    
11.01.2017 / 12:40
2

Another way to solve is to join each group of three and check that all are equal, note the initial value of $i has gone from zero to one, to identify the multiples of three:

$sorteados = array();
for($i = 1; $i<10; $i++){
    $numero = mt_rand(1,9);
    $premio = mt_rand(1,20);
    $sorteados[] = $numero;

    if($i % 3 === 0){
        if($sorteados[0] == $sorteados[1] && $sorteados[1] == $sorteados[2]){
            printf('Iguais: %s - %s - %s | prêmio: %s <br>', $sorteados[0], $sorteados[1], $sorteados[2], array_sum($sorteados));
        }else{
            printf('Sorteados: %s - %s - %s | prêmio: %s  <br>', $sorteados[0], $sorteados[1], $sorteados[2], $premio);
        }
        $sorteados = array();
    }
}

Possible output:

Iguais: 8 - 8 - 8    | prêmio: 24
Sorteados: 8 - 1 - 1 | prêmio: 17
Sorteados: 4 - 7 - 8 | prêmio: 12 
    
11.01.2017 / 12:50