<?php function getRandom($values, $weights) { $count = count($values); $i = 0; $n = 0; $num = mt_rand(0, array_sum($weights) * 100) / 100; while($i < $count) { $n += $weights[$i]; if($n >= $num) break; $i++; } return $values[$i]; } $values = [1,2,3,4]; $weights = [60.0000,30.0000,9.9800,.0200]; $counts = array_combine($values, array_fill(0, count($values), 0)); for ($i = 0; $i < 100000; $i++) { $counts[getRandom($values, $weights)]++; } echo "value\tweight\tcount\t%\n"; for ($i = 0; $i < count($values); $i++) { echo $values[$i] . "\t" . $weights[$i] . "\t" . $counts[$values[$i]] . "\t" . round($counts[$values[$i]]/array_sum($counts)*100, 2) . "\n"; }
You have javascript disabled. You will not be able to edit any code.