Monday, June 27, 2011

Simple javascript explanation of Monty Hall's game show problem


I have created a simple javascript program that will demonstrate how you can increase your probability of winning in the "Monty Hall's Let's Make A Deal game show"


 <script type="text/javascript">  
      var samplesize = 1000;  // Sample size
      var shuffle = function(v){  
           for(var j, x, i = v.length; i; j = parseInt(Math.random() * i), x = v[--i], v[i] = v[j], v[j] = x);  
           return v;  
      };  
      var a=[0,0,1]  

      var randomIndex;  
      var randomIndex1,randomIndex2,randomIndex3;  
      var randomDraw;  
      var result="";  
      var switched=0;  
      var won=0;  
      var switchedAndWon = 0;  
      var switchedAndLost=0;  
      var keptAndWon=0;  
      var keptAndLost=0;  
      var hasswitched;  
      var haswon;  
      for(var i=0; i<samplesize; i++){  
           // Step 1: Shuffle it first  
           a = shuffle(a);  
           // Step 2: Your first draw:   
           randomIndex1 = Math.floor(Math.random()*3);  
           randomDraw = a[randomIndex1];  
           // Step 3: Monty's draw:   
           randomIndex2 = -1;  
           while(randomIndex2 == randomIndex1 || randomIndex2 == -1 || a[randomIndex2] == 1){  
                randomIndex2 = Math.floor(Math.random()*3);  
           }  
           randomDraw = a[randomIndex2];  
           // Step 4: Your second draw:   
           randomIndex3 = -1;  
           while(randomIndex3 == randomIndex2 || randomIndex3 == -1){  
                randomIndex3 = Math.floor(Math.random()*3);  
           }  
           randomDraw = a[randomIndex3];  
           // Step 5: Now calculate  
           hasswitched = (randomIndex1 != randomIndex3);  
           haswon = randomDraw;  
           if(hasswitched){  
                switched++;  
           }  
           if(haswon){  
                won++;  
           }  
           if(hasswitched && haswon){  
                switchedAndWon++;  
           }else if(hasswitched && !haswon){  
                switchedAndLost++;  
           }else if(!hasswitched && haswon){  
                keptAndWon++;  
           }else if(!hasswitched && !haswon){  
                keptAndLost++;  
           }  
           //Push the results:  
           result += "["+String(a)+"] You: "+randomIndex1+", Monty: "+randomIndex2+", You: "+randomIndex3+"(switched: "+(randomIndex1 != randomIndex3)+")<br/>";  
      }  
      //document.write("<br/>switchedAndWon = "+switchedAndWon+" of total "+samplesize+" results");  
      document.write("<br/>switchedAndWon = "+switchedAndWon+" (There! Almost twice of keptAndWon)");  
      document.write("<br/>switchedAndLost = "+switchedAndLost);  
      document.write("<br/>keptAndWon = "+keptAndWon);  
      document.write("<br/>keptAndLost = "+keptAndLost);  
      document.write("<br/><br/>");  
      document.write(result);  
 </script>  

I hope you enjoy it.

No comments: