How do I scroll through the data of an array, to perform a draw with odds proportions? [duplicate]

this question already has answers here : Random within a random (2 responses) Closed 1 year ago.

Following guys, I was studying how I could create a small drawing application that was simple and fair and at the same time has odds, in my research I found several ways to make a random choice of the data stored within an array, using the rand(), mt_rand() and array_rand() commands and even using the shuffle() function to help shuffle.

Here Comes the question, to make a draw normal where data has the same chance (probability) of being chosen these functions by themselves is enough and works very well, however I would like to know how I could add the element "Chance or probability" that a data stored within the array or in the database can be chosen

I will try to give an example of what I would like to try to do:

1-example that has equal chances:

<?php
//Variável que armazena os dados do array
$escolher = array("Arroz", "Feijão", "Macarrão", "Pizza", "Hamburguer");

//Variável que irá armazenar o elemento escolhido aleatóriamente
$resultado = array_rand($escolher);

//Imprimindo o Resultado na tela
echo 'O Alimento escolhido foi: ' . $resultado; //(Arroz)
?>

2-example that adds amount of odds or probabilities of an element being chosen:

<?php
/*
Variável que armazena os dados do array,
repetindo os dados de acordo com o numero de chances que cada um tem de ser escolhido sendo,
Arroz = 2, Feijão = 1, Macarrão = 4, Pizza = 3, Hamburguer = 4
*/
$escolher = array(
"Arroz", "Arroz",
"Feijão",
"Macarrão", "Macarrão", "Macarrão", "Macarrão",
"Pizza", "Pizza", "Pizza",
"Hamburguer", "Hamburguer", "Hamburguer", "Hamburguer"
);

//Variável que irá armazenar o elemento escolhido aleatóriamente
$resultado = array_rand($escolher);

//Imprimindo o Resultado na tela
echo 'O Alimento escolhido foi: ' . $resultado; //(Macarrão)
?>

Well, both examples work by returning a random result, but in the case I don't know if the repetition that occurs in Example 2 is reliable, and I would like to do the second example in a way where I don't have to keep repeating the same information several times within the array to increase or decrease the chances of it being chosen, the chance that each element has, and thus be able to manipulate who has more priority to be chosen and who has less priority.

I was taking a look at these articles here from SOpt, but I was more lost than blind in shooting, perhaps due to my level of knowledge that is not very high, so I would like your help, thank you already.

These are the links of the articles I cited:

Https://pt.stackoverflow.com/questions/206164/sistema-de-sorteio

Drawing strings from an array with weight

 1
Author: Glorfindel, 2019-08-17

2 answers

I believe a better approach would be to turn these weights into indices so perform a random to check the range drawn.

    <?php

        $weights = ['arroz' => 2,  "feijao" => 1, "macarrao" => 4, "pizza" => 3, "hamburguer" => 4];
        $max = array_sum($weights);
        $sortIndex = rand(1, $max);
        $sort = null;
        $offset = 0;

        foreach ($weights as $key => $value) {
            $offset += $value;
            if ($sortIndex <= $offset) {
                $sort = $key;
                break;
            }
        }

        echo $sort;
 1
Author: Lucas Carvalho, 2019-08-19 13:18:08

Good Morning, hope to help.

Your example:

$tarefas = array(
    3 => 'Comer Pizza';
    1 => 'Comer Hamburguer'; 
    5 => 'Comer Arroz com Feijao';
    3 => 'Comer Macarrao';
    1 => 'Comer Pao com Mortadela';
);

$min = 1;  //Valor Minimo
$max = 13; //Máximo com base na soma das Chaves do array

$x = mt_rand($min, $max);
echo $tarefas[$x];

$x = mt_rand(1, 13); //Saída Ex: 5
echo $tarefas[5]; // Comer Arroz com Feijao

Make the changes below to help you, I explained in the Code:

<?php
    $tarefas = array(
        3 => 'Comer Pizza',
        1 => 'Comer Hamburguer', 
        5 => 'Comer Arroz com Feijao',
        3 => 'Comer Macarrao',
        1 => 'Comer Pao com Mortadela'
    );

    //1 - Organizar as chaves, com isto, não havendo mais repetidos e sim distintos.
    $tarefasN = array_values($tarefas);

    //2 - array_rand, escolhe já de forma aleatoria um ou mais indice no array
    $aleatorio = array_rand($tarefasN, 1); //aonde está 1 vc pode usar para ter retorno, exemplo, se quer 2 retornos, ou 3, 4 e assim por diante

    echo $aleatorio . ' - '; //gera índice aleatório

    echo $tarefasN[$aleatorio]; // retorno já com o array organizado
 1
Author: , 2019-08-17 11:46:10