Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- "use strict";
- function newGame(amountDoors) {
- const doors = []
- // Fill door array with zeroes
- for (let i = 0; i < amountDoors; i++) {
- doors.push({
- thing: "goat",
- revealed: false
- });
- }
- // Add a car somewhere
- doors[Math.floor(Math.random() * amountDoors)].thing = "car";
- return {
- wins: 0,
- losses: 0,
- doors: doors,
- choice: null
- };
- }
- function pick(game, index) {
- game.choice = index;
- return game;
- }
- function reveal(game) {
- if (game.doors[game.choice].thing === "goat") {
- // Player chose goat
- for (let i = 0; i < game.doors.length; i++) {
- // Reveal everything but the player's choice and the car
- if (i !== game.choice && game.doors[i].thing !== "car") {
- game.doors[i].revealed = true;
- }
- }
- } else {
- // Player chose car
- let stayClosed;
- do {
- stayClosed = Math.floor(Math.random() * game.doors.length);
- } while (stayClosed === game.choice);
- for (let i = 0; i < game.doors.length; i++) {
- // Reveal everything but the player's choice and one random goat
- if (i !== game.choice && i !== stayClosed) {
- game.doors[i].revealed = true;
- }
- }
- }
- return game;
- }
- function switchChoice(game) {
- let closedCarDoor = null;
- let closedGoatDoor = null;
- for (let i = 0; i < game.doors.length; i++) {
- if (game.doors[i].thing === "car") {
- closedCarDoor = i;
- } else if (game.doors[i].thing === "goat"){
- // is goat
- if (!game.doors[i].revealed) {
- closedGoatDoor = i;
- }
- }
- if (closedCarDoor !== null && closedGoatDoor !== null) {
- break;
- }
- }
- game.choice = game.choice === closedCarDoor ? closedGoatDoor : closedCarDoor;
- return game;
- }
- function win(game) {
- return game.doors[game.choice].thing === "car";
- }
- // main
- function main(doSwitch) {
- if (doSwitch) console.log("Switching enabled!");
- let wins = 0;
- let losses = 0;
- for (let i = 0; i < 10000; i++) {
- const game = newGame(3);
- pick(game, Math.floor(Math.random() * 3));
- reveal(game);
- if (doSwitch) switchChoice(game);
- if (win(game)) {
- wins++;
- } else losses++;
- }
- console.log("{Wins: " +wins + ", Losses: " + losses + "}");
- }
- main(false);
- main(true);
Add Comment
Please, Sign In to add comment