Monty Hall Problem Simulator


SUBMITTED BY: Guest

DATE: Dec. 8, 2013, 7:39 a.m.

FORMAT: Text only

SIZE: 2.1 kB

HITS: 928

  1. function rand(n) {
  2. return Math.floor(Math.random() * n);
  3. }
  4. function Game() {
  5. this.doors = ['closed', 'closed', 'closed'];
  6. this._goat = rand(3); // @private
  7. }
  8. Game.prototype.reveal = function(picked) {
  9. var options = [];
  10. for (var i = 0; i < 3; i++) {
  11. if (i !== picked && i !== this._goat) {
  12. options.push(i);
  13. }
  14. }
  15. this.doors[options[rand(options.length)]] = 'open';
  16. return this;
  17. };
  18. // Strategy prototype (abstract)
  19. function Strategy() {
  20. this.picked = null;
  21. }
  22. Strategy.prototype.firstPick = function() {
  23. return this.picked = rand(3);
  24. };
  25. Strategy.prototype.finalPick = function() {
  26. throw new Error('unimplemented');
  27. };
  28. function HoldStrategy() {
  29. }
  30. HoldStrategy.prototype = Object.create(Strategy.prototype);
  31. HoldStrategy.prototype.finalPick = function(game) {
  32. return this.picked;
  33. };
  34. function SwitchStrategy() {
  35. }
  36. SwitchStrategy.prototype = Object.create(Strategy.prototype);
  37. SwitchStrategy.prototype.finalPick = function(game) {
  38. for (var i = 0; i < 3; i++) {
  39. if (i !== this.picked && game.doors[i] !== 'open') {
  40. return i;
  41. }
  42. }
  43. return null;
  44. };
  45. Game.monteCarlo = function(n, Strategy) {
  46. var total = 0;
  47. for (var i = 0; i < n; i++) {
  48. var game = new Game();
  49. var strategy = new Strategy();
  50. game.reveal(strategy.firstPick());
  51. total += (strategy.finalPick(game) === game._goat) ? 1 : 0;
  52. };
  53. return total / n;
  54. };
  55. Usage:
  56. Game.monteCarlo(1000000, HoldStrategy);
  57. // => 0.333622
  58. Game.monteCarlo(1000000, SwitchStrategy);
  59. // => 0.667626
  60. More strategies are possible:
  61. function CheatStrategy() {
  62. }
  63. CheatStrategy.prototype = Object.create(Strategy.prototype);
  64. CheatStrategy.prototype.finalPick = function(game) {
  65. return game._goat;
  66. };
  67. Game.monteCarlo(1000000, CheatStrategy);
  68. // => 1

comments powered by Disqus