- var_dump: documentation ( source)
- array_sum: documentation ( source)
- mt_rand: documentation ( source)
- array_fill: documentation ( source)
- range: documentation ( source)
<?php
$iter = 0;
function weight($array)
{
global $iter;
$sum = array_sum($array);
$rnd = mt_rand(0,$sum);
foreach($array as $k=>$v)
{
$iter++;
if($rnd <= $v)
{
return $k;
}
$rnd = $rnd - $v;
}
}
$weights = range(0, 1000000);
$values = array_fill(0, count($weights), 0);
for ($x = 0; $x < 1000; $x++)
{
$w = weight($weights);
$values[$w] = $values[$w] + 1;
}
echo "$iter iterations performed";
var_dump($values);