Skip to content

Instantly share code, notes, and snippets.

@clasen
Last active March 13, 2017 16:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save clasen/5415fb1dce23d063da0efc18054b73f7 to your computer and use it in GitHub Desktop.
Save clasen/5415fb1dce23d063da0efc18054b73f7 to your computer and use it in GitHub Desktop.
<?php
class Chances {
protected $max;
protected $pie;
protected $rnd;
public function __construct($max = 100) {
$this->max = $max;
$this->pie = $max;
$this->rnd = rand(1, $max);
}
public function percent($i) {
$this->pie -= $i;
return $this->rnd <= ($this->max - $this->pie);
}
}
// Test
$count = [];
for ($i=0; $i < 10100; $i++) {
$chances = new Chances();
if ($chances->percent(15)) {
$count[15] = isset($count[15]) ? $count[15] + 1 : 1;
} elseif ($chances->percent(30)) {
$count[30] = isset($count[30]) ? $count[30] + 1 : 1;
} elseif ($chances->percent(55)) {
$count[55] = isset($count[55]) ? $count[55] + 1 : 1;
} else {
// fail
$count[0] = isset($count[0]) ? $count[0] + 1 : 1;
}
}
print_r($count);
/* Output
(
[30] => 3057
[55] => 5533
[15] => 1510
)
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment