Created
June 16, 2015 23:03
-
-
Save WillJW/1cd713eb0cc622a02260 to your computer and use it in GitHub Desktop.
The Monty Hall Problem
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 | |
class MontyHall | |
{ | |
const CAR = 'Car'; | |
const GOAT = 'Goat'; | |
public $doors; | |
public $choice; | |
public function __construct() | |
{ | |
// Setup doors with goats | |
$this->doors = array_fill(0, 3, static::GOAT); | |
// Add a car to one random door | |
$key = array_rand($this->doors); | |
$this->doors[$key] = static::CAR; | |
} | |
public function makeChoice() | |
{ | |
$this->choice = array_rand($this->doors); | |
} | |
public function switchChoice() | |
{ | |
// Find a goat from the 2 unpicked doors | |
foreach ($this->doors as $key => $value) { | |
// Skip the door we've already picked | |
if ($key === $this->choice) { | |
continue; | |
} | |
// Reveal the first goat we find | |
if ($value === static::GOAT) { | |
$reveal = $key; | |
break; | |
} | |
} | |
// Switch our choice to the remaining door | |
for ($i = 0; $i < count($this->doors); $i++) { | |
if ($i !== $this->choice && $i !== $reveal) { | |
$this->choice = $i; | |
break; | |
} | |
} | |
} | |
public function isCorrect() | |
{ | |
return ($this->doors[$this->choice] === static::CAR); | |
} | |
} | |
$stick = 0; | |
$switch = 0; | |
// Run through 1,000,000 times | |
for ($i = 0; $i < 1000000; $i++) { | |
$montyHall = new MontyHall; | |
$montyHall->makeChoice(); | |
if ($montyHall->isCorrect()) { | |
$stick++; | |
} | |
$montyHall = new MontyHall; | |
$montyHall->makeChoice(); | |
$montyHall->switchChoice(); | |
if ($montyHall->isCorrect()) { | |
$switch++; | |
} | |
} | |
echo 'Stick: ' . round($stick / 1000000 * 100, 2) . '% correct' . PHP_EOL; | |
echo 'Switch: ' . round($switch / 1000000 * 100, 2) . '% correct' . PHP_EOL; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment