How to make a random choice without repeating PHP

Asked

Viewed 217 times

0

I am doing a back end course with PHP and I am not able to solve the following exercise

    <?php
    
    $animais_detalhes = [
        'cachorro' => [
            'nome' => 'Cachorro',
            'caracteristicas' => [
                ['mora numa casinha', 'cachorro/mora_numa_casinha.jpg'],
                ['tem patas', 'cachorro/tem_patas.jpg']
            ]
        ],
        'coruja' => [
            'nome' => 'Coruja',
            'caracteristicas' => [
                ['gosta da noite', 'coruja/gosta_da_noite.jpg'],
                ['tem olhos grandes', 'coruja/tem_olhos_grandes.jpg']
            ]
            ],
            'cavalo' => [
                'nome' => 'Cavalo',
                'caracteristicas' => [
                    ['tem pernas longas', 'cavalo/tem_pernas_longas.jpg'],
                    ['tem o casco duro', 'cavalo/tem_casco_duro.jpg']
                ]
        ],
        'gato' => [
                'nome' => 'Gato',
                'caracteristicas' => [
                    ['cospe bolas de pelo', 'gato/bola_de_pelo.jpg'],
                    ['anda por cima das coisas', 'gato/anda_cima_coisas.jpg']
                ]
        ]
    ];
    
    $animais = array_keys($animais_detalhes);
    $escolha_aleatoria = rand(0, 3);
    $animal_escolhido = $animais_detalhes[$animais[$escolha_aleatoria]];
    ?>

<!doctype html>
<html lang="en">
    <head>
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
        <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css" integrity="sha384-9aIt2nRpC12Uk9gS9baDl411NQApFmC26EwAOH8WgZl5MYYxFfc+NcPb1dKGj7Sk" crossorigin="anonymous">
        <title>Hello, world!</title>

        <style>
            body {
                background: lightgreen;
            }

            .card-image img {
                object-fit: cover;
                object-position: center;
                width: 100%;
                max-height: 200px;
            }

            img.img-animal {
                object-fit: none;
                object-position: center;
                width: 100%;
                max-height: 200px;
            }
        </style>
    </head>
    <body>
        <div class="container-fluid p-4 pb-2" style="background: lightskyblue">
            <div class="row mt-2">
                <div class="col-md-2"></div>
                <div class="col-md-4">
                    <div class="card card-image d-block">
                        <img src="./imagens/<?=$animal_escolhido['caracteristicas'][0][1]?>" class="card-img-top" alt="<?=$animal_escolhido['caracteristicas'][0][0]?>">
                        <div class="card-body">
                            <p class="card-text"><?=$animal_escolhido['caracteristicas'][0][0]?></p>
                        </div>
                    </div>
                </div>
                <div class="col-md-4">
                    <div class="card card-image d-block">
                        <img src="./imagens/<?=$animal_escolhido['caracteristicas'][1][1]?>" class="card-img-top" alt="<?=$animal_escolhido['caracteristicas'][1][0]?>">
                        <div class="card-body">
                            <p class="card-text"><?=$animal_escolhido['caracteristicas'][1][0]?></p>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        <div class="container-fluid p-2 mt-3" style="background: lightgreen">
            <div class="row">
                <div class="col-md-3"></div>
                <div class="col-md-3">
                    <a href="votar.php?apresentado=<?=$animais[$escolha_aleatoria]?>&escolhido=1">
                        <img width="256" src="./imagens/<?=$animais[$escolha_aleatoria] ?>.png" class="img-fluid" alt="mora numa casinha" />
                    </a>
                </div>
                <div class="col-md-3">
                    <a href="votar.php?apresentado=<?=$animais[$escolha_aleatoria]?>&escolhido=2">
                        <!-- deixe dinâmico esta imagem abaixo -->
                        <img width="256" src="./imagens/cachorro.png" class="img-fluid" alt="mora numa casinha" />
                    </a>
                </div>
                <div class="col-md-3"></div>
            </div>
        </div>

        <script src="https://code.jquery.com/jquery-3.5.1.slim.min.js" integrity="sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj" crossorigin="anonymous"></script>
        <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/umd/popper.min.js" integrity="sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo" crossorigin="anonymous"></script>
        <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/js/bootstrap.min.js" integrity="sha384-OgVRvuATP1z7JjHLkuOU7Xw704+h835Lr+6QL9UvYjZE3Ipu6Tp75j7Bh/kR0JKI" crossorigin="anonymous"></script>
    </body>
</html>

What I need to do is this:

  1. Correct the code so that the correct animal is no longer always the first and then pass this order to be random.

    • There are no problems in the correct animal being the first a few times, the problem is it always be. This should be random, random.
  2. Correct the code so that the dog or any other animal does not appear twice as the only two options.

    • You need to show the right animal and another animal, anyone, as long as it’s not the same.

I’m trying this way

$animais = array_keys($animais_detalhes);

$escolha_aleatoria = rand(0, count($animais)-1);

$animal_escolhido = $animais_detalhes[$animais[$escolha_aleatoria]];

$outroAnimal = rand(0, count($animais)-1);

if ($animal_escolhido == $outroAnimal){

    $outroAnimal = rand(0, count($animais)-1);
}

$escolhas = [$escolha_aleatoria, $outroAnimal];

shuffle($escolhas);

    $escolha1 = $escolhas[0];

    $escolha2 = $escolhas[1];

But sometimes it still appears the same animal 2x.

  • I couldn’t understand the question. You want someone to do the exercise for you?

  • Explain me how doing would be enough, I tried some options to leave the image randomized and not appear 2x, but I’m not getting.

  • a hint, you check only once in the 'if' if the animal is not duplicated, what you could do is use 'while' instead of 'if'

2 answers

0

Instead of "IF"(se), use "WHILE"(while):

   while ($animal_escolhido == $outroAnimal){

        $outroAnimal = rand(0, count($animais)-1);´

    }

Documentation

0


If so the $animal_escolhido as the other should be chosen randomly, do not need to choose one, and then try to catch the other. You can catch both at once.

Just grab the key array you already have (returned by array_keys), shuffle him with shuffle and get the first 2 keys:

$chaves = array_keys($animais_detalhes);
shuffle($chaves);
$animal_escolhido = $animais_detalhes[$chaves[0]];
$outro = $animais_detalhes[$chaves[1]];

Like shuffle shuffles the keys, I guarantee that when picking up the first and second elements, they will be random.

Including, this idea of shuffling all the elements and then taking only the amount you need is known as fisher-yates algorithm.

Browser other questions tagged

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