Guest User

Untitled

a guest
Oct 18th, 2018
98
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.50 KB | None | 0 0
  1. "use strict";
  2.  
  3. function newGame(amountDoors) {
  4. const doors = []
  5.  
  6. // Fill door array with zeroes
  7. for (let i = 0; i < amountDoors; i++) {
  8. doors.push({
  9. thing: "goat",
  10. revealed: false
  11. });
  12. }
  13.  
  14. // Add a car somewhere
  15. doors[Math.floor(Math.random() * amountDoors)].thing = "car";
  16.  
  17. return {
  18. wins: 0,
  19. losses: 0,
  20. doors: doors,
  21. choice: null
  22. };
  23. }
  24.  
  25. function pick(game, index) {
  26. game.choice = index;
  27. return game;
  28. }
  29.  
  30. function reveal(game) {
  31. if (game.doors[game.choice].thing === "goat") {
  32. // Player chose goat
  33. for (let i = 0; i < game.doors.length; i++) {
  34. // Reveal everything but the player's choice and the car
  35. if (i !== game.choice && game.doors[i].thing !== "car") {
  36. game.doors[i].revealed = true;
  37. }
  38. }
  39. } else {
  40. // Player chose car
  41. let stayClosed;
  42. do {
  43. stayClosed = Math.floor(Math.random() * game.doors.length);
  44. } while (stayClosed === game.choice);
  45.  
  46. for (let i = 0; i < game.doors.length; i++) {
  47. // Reveal everything but the player's choice and one random goat
  48. if (i !== game.choice && i !== stayClosed) {
  49. game.doors[i].revealed = true;
  50. }
  51. }
  52. }
  53. return game;
  54. }
  55.  
  56. function switchChoice(game) {
  57. let closedCarDoor = null;
  58. let closedGoatDoor = null;
  59.  
  60. for (let i = 0; i < game.doors.length; i++) {
  61. if (game.doors[i].thing === "car") {
  62. closedCarDoor = i;
  63. } else if (game.doors[i].thing === "goat"){
  64. // is goat
  65. if (!game.doors[i].revealed) {
  66. closedGoatDoor = i;
  67. }
  68. }
  69. if (closedCarDoor !== null && closedGoatDoor !== null) {
  70. break;
  71. }
  72. }
  73. game.choice = game.choice === closedCarDoor ? closedGoatDoor : closedCarDoor;
  74. return game;
  75. }
  76.  
  77. function win(game) {
  78. return game.doors[game.choice].thing === "car";
  79. }
  80.  
  81.  
  82. // main
  83. function main(doSwitch) {
  84. if (doSwitch) console.log("Switching enabled!");
  85.  
  86. let wins = 0;
  87. let losses = 0;
  88.  
  89. for (let i = 0; i < 10000; i++) {
  90. const game = newGame(3);
  91. pick(game, Math.floor(Math.random() * 3));
  92. reveal(game);
  93. if (doSwitch) switchChoice(game);
  94.  
  95. if (win(game)) {
  96. wins++;
  97. } else losses++;
  98. }
  99.  
  100. console.log("{Wins: " +wins + ", Losses: " + losses + "}");
  101. }
  102.  
  103. main(false);
  104. main(true);
Add Comment
Please, Sign In to add comment