# Monty Hall problem - TSQL

Following on from this morning's post about the Monty Hall problem, and proving it in PHP I figured I'd prove it in TSQL as well.

So here is my SQL version.

To maintain consistency with my PHP version, I've made it output similar text, so the results are along the lines of:

Monty Hall Problem

This is a simple TSQL query to prove the Monty Hall problem [http://en.wikipedia.org/wiki/Monty_hall_problem]

------------------------

The Results are in:

------------------------

Out of 10000 games, the contestant was right to swap 66.94% of the time and wrong 33.06% of the time

The TSQL version is a bit more elegant with regards to working out which door to open for the contestant, as it is a simple statement of

SELECT TOP 1 @Opened = DoorNumber

FROM @Doors

WHERE DoorNumber NOT IN (@Prize, @Picked)

ORDER BY NEWID()

making the most of set theory to enable the exclusion of the @Prize door and the @Picked door as opposed to the same thing in my PHP code

$remaining = array();

/* the gameshow host opens a door which has nothing behind it, so the gameshow host knows where the prize is

but can't choose to open the door the contestant has chosen, so remove both picked and prize from the options,

this leaves either one of two doors that can be opened, so pick one randomly */

for ($i=0; $i<3; $i ++)

{

switch($doors[$i])

{

case $prize:

break;

case $picked:

break;

default:

array_push($remaining,$doors[$i]);

}

}

$opened = $remaining[array_rand($remaining)];

which is all a bit more procedural and, at least to my mind, less elegant - but then again I like the syntax of SQL which either makes me a freak or a masochist (according to at least one colleague)