Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <?php
- // Based on code from:
- // http://stackoverflow.com/questions/14389180/algorithm-for-probability-when-looping-over-a-randomly-ordered-array
- // http://math.stackexchange.com/questions/280792/determining-probability-in-a-random-loop/280948#280948
- // -------------
- // Taken from php.net/shuffle user notes
- function shuffle_assoc($array) {
- $keys = array_keys($array);
- shuffle($keys);
- foreach($keys as $key) {
- $new[$key] = $array[$key];
- }
- return $new;
- }
- $i = 1000000; // How many tests to perform
- // This is my rule list. Each key is a simple color
- // and each value is a probability represented as a percent
- $rules = array(
- 'black' => 20,
- 'white' => 10,
- 'red' => 40,
- 'green' => 5,
- 'blue' => 25,
- );
- // Initialize the scores array with all 0's
- // The "outs" will be used when the probability does not
- // occur in any of the rules
- $scores = array('outs' => 0);
- foreach($rules as $k => $v) {
- $scores[$k] = 0;
- }
- $count = count($rules);
- for($x = 0; $x < $i; $x++) {
- $rules = shuffle_assoc($rules);
- $accumulated_probability = 0;
- $rand = mt_rand(1,100);
- foreach($rules as $k => $probability) {
- $actual_probability = $probability + $accumulated_probability;
- $accumulated_probability = $probability + $accumulated_probability;
- if($rand > $actual_probability) {
- continue;
- } else {
- $scores[$k]++;
- continue 2;
- }
- }
- $scores['outs']++;
- }
- foreach($scores as $k => $v) {
- echo "$k: " . (($v/$i)*100) . "% ($v/$i)\n";
- }
- ?>
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement