<?php $valueWeights = [ 149 => 55.555, 130 => 10.0050, 131 => 5, 132 => 5.2, 133 => 10, 134 => 10.24, 135 => 5 ]; $mostDecimals = 0; // not bothering to validate against infinite and extremely fringe case floats foreach ($valueWeights as $value => $weight) { $tempDecimals = 0; while ((string)$weight !== (string)floor($weight)) { $weight *= 10; // this is not permanently mutating the weight ++$tempDecimals; } $mostDecimals = max($mostDecimals, $tempDecimals); } echo "Most Decimals: {$mostDecimals}\n"; $factor = pow(10, $mostDecimals); echo "Factor: " , $factor , "\n"; $totalWeight = (array_sum($valueWeights) - 1) * $factor; for ($i = 0; $i < 10; ++$i) { $rand = mt_rand(0, $totalWeight); echo "\nRand: " , $rand , "\n"; $cumulativeScaledWeight = 0; foreach ($valueWeights as $value => $weight) { $cumulativeScaledWeight += $weight * $factor; if ($rand < $cumulativeScaledWeight) { echo "Value: {$value}\n"; break; } } }
You have javascript disabled. You will not be able to edit any code.