Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Random value from array by weight in php

I understand that this question has likely been asked, but I don't understand the prior questions enough to know if they do what I want.

$fruits = array('20' => 'apple', '40' => 'orange', '40' => 'pear');

The keys are percentages of the chance of value getting picked. I would like to mt_rand() a number between 0 and 99 and return a value from $fruits based on those percentages.

It's very possible I'm so confused because I don't know how to explain what I'm looking for.

Thank you in advance for the help.

Edit: want a random value from $fruits, based on these chances:

I want a 40% chance of getting an orange, a 40% chance of getting a pear, and an 80% chance of getting an apple.

Edit: To further clarify, since either a lot of the answers got it wrong, (or I just don't understand their code), I needed a result regardless of what number I pick, not just 20, 40, or 40.

like image 471
Drazisil Avatar asked Sep 24 '12 19:09

Drazisil


2 Answers

First of all, your array only has two items (apple and pear) because pear overwrites orange due to having the same key. So use the opposite order. Also, don't put quotes around the integers:

$fruits = array('apple' => 20, 'orange' => 40, 'pear' => 40);

You should choose a random number, then compare each weight of the array plus the sum of the previous weights until you get a match:

$rand = rand(1,100);
$sum = 0;
$chosenFruit;

foreach ($fruits as $f=>$v) {
    $sum += $v;
    if ( $sum >= $rand ) {
        $chosenFruit = $f;
        break;
    }
}

echo "We have chosen the {$chosenFruit}!";

You could even make the procedure more resilient by replacing the value of 100 in the rand() function with a calculated sum of the $fruits array values.

like image 145
dotancohen Avatar answered Sep 17 '22 18:09

dotancohen


I think something like this will do what you want:

sample

(click the submit button multiple times on the sample to get the code to re-execute)

$fruits = array('apple' => '20', 'orange' => '40', 'pear' => '40');

$newFruits = array();
foreach ($fruits as $fruit=>$value)
{
    $newFruits = array_merge($newFruits, array_fill(0, $value, $fruit));
}

$myFruit = $newFruits[array_rand($newFruits)];

This creates an array ($newFruits), which is a numerically-indexed array with 100 elements. 20 of those elements are 'apple', 40 are 'orange', and 40 are 'pear'. Then we select a random index from that array. 20 times out of 100 you will get 'apple', 40 times out of 100 you will get 'orange', and 40 times out of 100 you will get 'pear'.

like image 37
Travesty3 Avatar answered Sep 19 '22 18:09

Travesty3