Ballot Simulator - PHP Online
Form of PHP Sandbox
Enter Your PHP code here for testing/debugging in the Online PHP Sandbox. As in the usual PHP files, you can also add HTML, but do not forget to add the tag <?php
in the places where the PHP script should be executed.
Result of php executing
Full code of Ballot Simulator.php
- <?php
- $blue = 225000;
- $red = 5000;
- $size_of_bags = 100;
- $blue_bags = 0;
- $red_bags = 0;
- $purple_bags = 0;
- $current_consecutive_blues = 0;
- $max_consecutive_blues = 0;
- $total_consecutive_blue_streaks = 0;
- // While we still have balls to put in bags.
- while ($blue > 0 || $red > 0) {
- // The current bag.
- $bag = ["blue" => 0, "red" => 0];
- // Loop through until you've filled up a bag.
- for ($i = 1; $i <= $size_of_bags; $i++) {
- // Do we still have at least 1 red or blue ball?
- if ($blue + $red != 0) {
- $odds_of_blue = round(100 * ($blue / ($blue + $red)));
- } else {
- // We don't so we're done.
- break;
- }
- // Pick a random number between 1 and 100.
- $rand = rand(1, 100);
- // Did we pick blue? Note if we're out of blue, then odds are 0. Out of red then odds are 100.
- if ($rand <= $odds_of_blue ){
- // Pull a blue ball out of the pool and add it to the bag.
- $blue--;
- $bag['blue']++;
- // We didn't pick blue, do we have any reds left to place?
- } elseif ($red > 0){
- // Put in a red ball.
- $red--;
- $bag['red']++;
- } else {
- // We're out of balls, do nothing.
- break;
- }
- }
- // We've filled up a bag, let's examine it.
- // Is it a bag of all blues?
- if ($bag['red'] == 0){
- // Add to the blue streak.
- $current_consecutive_blues++;
- // Add to our count of all blue bags.
- $blue_bags++;
- // Otherwise it's an all red bag or a purple bag.
- } else {
- // Have we had a streak of blue bags? A streak is more than 1 blue bag.
- if ($current_consecutive_blues > 1){
- // We have a new blue streak. Then add to the streak count.
- $total_consecutive_blue_streaks++;
- // Was this streak higher than our max streak?
- if ($current_consecutive_blues > $max_consecutive_blues){
- // It was so set the max streak count to this streak.
- $max_consecutive_blues = $current_consecutive_blues;
- }
- }
- // Reset our blue streak.
- $current_consecutive_blues = 0;
- // Is it a red or purple bag?
- if ($bag['blue'] == 0){
- // All red bag. Count it.
- $red_bags++;
- } else {
- // Then it's a purple bag.
- $purple_bags++;
- }
- }
- }
- $data = ["BLUE BAGS" => $blue_bags, "RED BAGS"=>$red_bags, "PURPLE BAGS"=>$purple_bags,
- "TOTAL BLUE STREAKS"=>$total_consecutive_blue_streaks, "MAX BLUE STREAK"=>$max_consecutive_blues] ;
- foreach ($data as $key=>$value){
- echo $key . ": " . $value . "\n";
- }