× Contact
Home ☰ Menu

Monty Hall problem

2017. 10. 18. 20:28

PHP

HTML

You are in a show. There are three doors and you have to select one door. Behind one door there is the prize: the car. Behind the two other doors you can only find a goat. The mission is simple: find the door which hides the car.

Two weeks ago I read this story in an article. First when I tried to imagine it, I was very skeptic. I coded this in PHP, which is simulating the Monty Hall problem. I was really surprised by the result.

We have the player, the showman and the system which is placing the two goats and the car behind the doors. The doors are placed in an array called $doors. In this case the for cycle runs for 1000 times. In each run we get a result. At the end we make a division to get the percentage value of the results.

You can try this code in this link 

$swap = 1;
$win = 0;

for($i=0;$i<1000;$i++){
	$doors = array(0, 1, 2);
	$doors2 = $doors;
	$system = rand(0,2);
	$player = rand(0, 2);

	unset($doors[$system]);
	unset($doors[$player]);
	$showman = end($doors);

	unset($doors2[$player]);
	unset($doors2[$showman]);
	$end = end($doors2);

	if($swap == 1){
		if($end == $system){
			$win++;	//The player wins, because of swapping
		}else{
			//The player loses, because of swapping
		}
	}else{
		if($player == $system){
			$win++; //The player wins, because of NOT swapping
		}else{
			//The player loses, because of NOT swapping
		}
	}
}

$result = $win/1000*100; //The result in percent
if($swap == 1)
	echo "The player swapped the door in every case: the possibility of winning is ".$result."%.";
else
	echo "The player NEVER swapped the door: the possibility of winning is ".$result."%.";

You can learn more from this brain teaser on Wikipedia.

Peter Sipos

I am a Web developer. I am developing in web languages like: PHP, HTML, JavaScript, jQuery, NodeJS. In the following posts you can learn some useful techniques.

6 articles available

More articles