There is an array of N elements, and an array of coefficients of probability of loss of each element. How can I implement the selection of a random element from this array?
I implemented it like this, but I think it is not very good.
$items = array(10, 20, 30); $factors = array(0.2, 0.5, 0.3); $values = array(); foreach ($factors as $indexFactors => $valueFactors) { $values[$indexFactors] = summ($factors, $indexFactors); } echo $items[ getIndex($values) ]; function getIndex($values) { $random = rand(0, 10) / 10; foreach ($values as $key => $value) { if ($random <= $value) return $key; } } function summ($array, $index) { if ($index) { return $array[$index] + summ($array, $index - 1); } else { return $array[$index]; } }