How can you implement a random drop percentage?
For example, there are 4 numbers (maybe more), 10, 15, 40, 12, but 10 percent has a dropout of 20%, 15 = 25%, 40 = 5%, and 12 = 50%, maybe there is some then the library?
How can you implement a random drop percentage?
For example, there are 4 numbers (maybe more), 10, 15, 40, 12, but 10 percent has a dropout of 20%, 15 = 25%, 40 = 5%, and 12 = 50%, maybe there is some then the library?
You need to fill the array with numbers so that the number of occurrences of each corresponds to the probability of its appearance in the output.
$a = array(10,15,40,12); $ver = array(20,25,5,50); unset($b); foreach($a as $key => $val) { for($i = 0; $i < $ver[$key]; $i++) { $b[] = $val; } } shuffle($b); printf($b[0]); We paint the coefficients (so that there are always percentages - we divide each by the sum of all and think what to do with accuracy) :
$chancesMap = [ 10 => 20, 15 => 25, 40 => 5, 12 => 50, ]; We write function:
/** * @param array $chancesMap Value => Chance * @return mixed * @throws Exception */ function getRandomValue($chancesMap) { $chancesSum = array_sum($chancesMap); $randomValue = rand(1, $chancesSum); foreach ($chancesMap as $value => $chance) { $randomValue -= $chance; if ($randomValue <= 0) { return $value; } } throw new Exception('Не может быть'); } Checking:
$testIterations = 10000; $results = array_flip(array_keys($chancesMap)); // запустим несколько раз.. for ($i = 0; $i < $testIterations; $i++) { $value = getRandomValue($chancesMap); $results[$value]++; } // проценты.. array_walk($results, function(&$count, $value) use ($testIterations) { $count = round($count / $testIterations * 100, 2); }); var_dump($results); It turns out:
array(4) { [10]=> float(19.7) [15]=> float(25.13) [40]=> float(5.39) [12]=> float(49.84) } I do not know about the library, it is hardly there. This is done simply
$a = array (10, 15, 40, 12); $prob = array (20, 45 /*20+25*/, 50 /*45+5*/, 100/*50+50*/) $r = rand(0, 100) /* включительно, желательно равномерное распределение */ for ($i = 0; $i<4; $i++) { if ($r <= $prob[$i]) return $a[$i]; } Sorry for the pseudocode, php I know very little.
Source: https://ru.stackoverflow.com/questions/548656/
All Articles