Monty Hall Simulation
by António Almeida
HTML
<h2>Monty Hall Simulation</h2>
<p>Player <b>don't change</b> his first choice</p>
<div class="result"><div></div></div>
<div class="result"><div></div></div>
<div class="result"><div></div></div>
<p>Player <b>always change</b> his choice</p>
<div class="result change"><div></div></div>
<div class="result change"><div></div></div>
<div class="result change"><div></div></div>
CSS
h2 { font-family: sans-serif; }
p, div { font-family: sans-serif; font-size: 12px;}
.result {
position: relative;
width: 400px;
height: 28px;
background-color: #d9534f;
line-height: 28px;
text-align: right;
margin-bottom: 10px;
box-shadow: 1px 1px 2px rgba(0,0,0,0.25);
color: #FFF;
}
.result > div {
position: absolute;
height: 28px;
width: 10px;
background-color: #5cb85c;
padding: 0 5px 0 0;
border-right: 1px solid #357535;
transition: width 1.6s;
}
JavaScript
function montyhallSimulation(playerChangeOpt, testcases)
{
playerChangeOpt = typeof playerChangeOpt !== 'undefined' ? playerChangeOpt : true;
testcases = typeof testcases !== 'undefined' ? testcases : 100;
var right = 0, wrong = 0;
for(i=0 ; i<testcases ; i++) {
var carPos = Math.floor(Math.random()*3);
var playerOpt = Math.floor(Math.random()*3);
var firstGoat;
while(firstGoat == undefined || firstGoat == carPos || firstGoat == playerOpt)
firstGoat = Math.floor(Math.random()*3);
if(playerChangeOpt) {
var newOpt;
while(newOpt == undefined || newOpt == firstGoat || newOpt == playerOpt)
newOpt = Math.floor(Math.random()*3);
playerOpt = newOpt;
}
carPos == playerOpt ? right++ : wrong++;
}
return right / testcases;
}
// Add testcases
var r, i, width = 400;
applyResult = (elem, result) => $(elem).css("width", (result*width) + "px").text(Math.floor(result*1000)/10 + " %");
// Player change his choice, 1k testcases
applyResult($(".result.change:eq(0)>div"), montyhallSimulation(true, 1000));
applyResult($(".result.change:eq(1)>div"), montyhallSimulation(true, 1000));
applyResult($(".result.change:eq(2)>div"), montyhallSimulation(true, 1000));
// Player do not change his choice, 1k testcases
applyResult($(".result:not(.change):eq(0)>div"), montyhallSimulation(false, 1000));
applyResult($(".result:not(.change):eq(1)>div"), montyhallSimulation(false, 1000));
applyResult($(".result:not(.change):eq(2)>div"), montyhallSimulation(false, 1000));