Monty Hall problem simulation

Overview

Monty Hall problem:

Suppose you’re on a game show, and you’re given the choice of three doors: Behind one door is a car; behind the others, goats. You pick a door, say No. 1 [but the door is not opened], and the host, who knows what’s behind the doors, opens another door, say No. 3, which has a goat. He then says to you, “Do you want to pick door No. 2?” Is it to your advantage to switch your choice?

It is interesting to create a program which simulates multiple games and shows whether switching is advantageous.

Source code

/**
 * Monty Hall problem simulation
 *
 * http://en.wikipedia.org/wiki/Monty_Hall_problem
 *
 * (C) 2012, Alex Netkachov, CC-BY-3.0
 */

/*globals console */

(function () {
    'use strict';

    /**
     * Randomly select door from the available doors.
     */
    function select(doors) {
        return doors[Math.floor((Math.random() * doors.length))];
    }

    /**
     * One game run.
     */
    function run() {
        var car, choice, opened, doors;
        // available doors:
        doors = [0, 1, 2];
        // place car behind the door:
        car = select(doors);
        // make choice:
        choice = select(doors);
        // the host opens the door with a goat behind it:
        opened = select(doors.filter(function (index) {
            return index !== car && index !== choice;
        }));
        // change the door:
        choice = doors.filter(function (index) {
            return index !== opened && index !== choice;
        }).pop();
        // return whether the player gets the car:
        return car === choice;
    }

    /**
     * Play game n times.
     */
    function play(n) {
        var index, wins = 0;
        for (index = 0; index < n; index += 1) {
            wins += run() ? 1 : 0;
        }
        return wins / n;
    }

    // run the game from 10 to 10^5 times and print wins/total:
    var games, power;
    for (games = 10, power = 1; power < 6; power += 1, games *= 10) {
        console.log('Wins(' + games + ')/' + games + ' = ' + play(games));
    }
}());

Results

Wins(10)/10 = 0.4
Wins(100)/100 = 0.64
Wins(1000)/1000 = 0.657
Wins(10000)/10000 = 0.6673
Wins(100000)/100000 = 0.66613