Created
December 31, 2011 07:26
-
-
Save LaffinToo/1543242 to your computer and use it in GitHub Desktop.
Weighted Probability - A simple weighted probability system
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
// Weight percentage system | |
// By: Laffin | |
// Gives weights to items, and randomly chooses items based on weight | |
$items = array( | |
array('lint',40), | |
array('copper coin',35), | |
array('silver coin',15), | |
array('gold coin',5), | |
array('bank note',5) | |
); | |
// How many loops should we do | |
$loops=500; | |
// Find the total weight of all items | |
$total_weight=0; | |
foreach($items as $key=>$val) | |
{ | |
$items[$key][2]=$total_weight; | |
$total_weight=$items[$key][3]=$val[1]+$total_weight; | |
} | |
// initialize our stat counter | |
foreach(array_keys($items) as $val) | |
$stat[$val]=0; | |
for($loop=0;$loop<$loops;$loop++) | |
{ | |
$chance=rand(0,$total_weight); | |
// Check Against Item Percent Markers | |
$marker=0; | |
foreach($items as $key=>$val) | |
if($chance<=$val[3]) break; | |
// Statistics | |
$stat[$key]++; | |
} | |
// Display Found stats for each item | |
header('Content-Type: text/plain'); | |
echo "Loop of {$loops}\n"; | |
echo "Just by weights\n"; | |
foreach($items as $key=>$val) | |
{ | |
echo "{$val[0]} found {$stat[$key]} times (%". (($stat[$key]/$loop)*100) .") base weight ($val[1]) base percentage(%". number_format((($val[1]/$total_weight)*100),2) .")\n"; | |
} | |
?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment