View difference between Paste ID: eB3TVP1E and
SHOW: | | - or go back to the newest paste.
1-
1+
<?php
2
  // Based on code from:
3
  // http://stackoverflow.com/questions/14389180/algorithm-for-probability-when-looping-over-a-randomly-ordered-array
4
  // http://math.stackexchange.com/questions/280792/determining-probability-in-a-random-loop/280948#280948
5
  // -------------
6
7
  // Taken from php.net/shuffle user notes
8
  function shuffle_assoc($array) {
9
    $keys = array_keys($array);
10
    shuffle($keys);
11
    foreach($keys as $key) {
12
      $new[$key] = $array[$key];
13
    }
14
    return $new;
15
  }
16
17
  $i = 1000000; // How many tests to perform
18
19
  // This is my rule list.  Each key is a simple color
20
  // and each value is a probability represented as a percent
21
  $rules = array(
22
    'black' => 20,
23
    'white' => 10,
24
    'red' => 40,
25
    'green' => 5,
26
    'blue' => 25,
27
  );
28
29
  // Initialize the scores array with all 0's
30
  // The "outs" will be used when the probability does not
31
  // occur in any of the rules
32
  $scores = array('outs' => 0);
33
  foreach($rules as $k => $v) { 
34
    $scores[$k] = 0;
35
  }
36
37
  $count = count($rules);
38
39
  for($x = 0; $x < $i; $x++) { 
40
    $rules = shuffle_assoc($rules);
41
42
    $accumulated_probability = 0;
43
    $rand = mt_rand(1,100);
44
    foreach($rules as $k => $probability) {
45
      $actual_probability = $probability + $accumulated_probability;
46
      $accumulated_probability = $probability + $accumulated_probability;
47
48
      if($rand > $actual_probability) { 
49
        continue; 
50
      } else {
51
        $scores[$k]++;
52
        continue 2;
53
      }
54
    }
55
    $scores['outs']++;
56
  }
57
58
59
  foreach($scores as $k => $v) { 
60
    echo "$k: " . (($v/$i)*100) . "% ($v/$i)\n";
61
  }
62
63
?>