<body>
  <div class="field">
    <label for="attempts">Number of Attempts:</label>
    <input id="attempts" type="number" value="100" />
  </div>
  <div class="field">
    <label for="switch">Switch Doors?</label>
    <input type="checkbox" id="switch" />
  </div>
  <div class="field">
    <button>Play!</button>
  </div>
  <div>
    <p id="result"></p>
  </div>
</body>
body {
  font-size: 16px;
  font-family: sans-serif;
  text-transform: uppercase;
}

.field {
  margin-bottom: 12px;
  border-bottom: 1px solid #ccc;
  padding: 16px;
}

button {
  font-size: 16px;
  font-family: sans-serif;
  text-transform: uppercase;
}

#result {
  padding-left: 16px;
}
import * as _ from "https://cdn.skypack.dev/lodash@4.17.21";

function getDoorSetup() {
  const setup = ["goat", "goat", "car"];
  return _.shuffle(setup);
}

function getDoorPick() {
  const doorPick = _.random(0, 2);
  return doorPick;
}

function getGoatNotAtDoorNumber(setup, doorNumber) {
  let goatDoorNumber;

  setup.forEach((item, itemNumber) => {
    if (item === "goat" && itemNumber !== doorNumber) {
      goatDoorNumber = itemNumber;
    }
  });

  return goatDoorNumber;
}

function getFinalPick(ourPick, revealedPick, changePick) {
  if (!changePick) {
    return ourPick;
  }

  const possibleDoorNumbers = [0, 1, 2];
  return possibleDoorNumbers.filter((doorNumber) => {
    if (doorNumber !== ourPick && doorNumber !== revealedPick) {
      return true;
    }
  })[0];
}

function playGame(switchDoors) {
  const setup = getDoorSetup();
  const ourDoorPick = getDoorPick();
  const revealedGoatPosition = getGoatNotAtDoorNumber(setup, ourDoorPick);
  const ourFinalPick = getFinalPick(
    ourDoorPick,
    revealedGoatPosition,
    switchDoors
  );

  if (setup[ourFinalPick] === "car") {
    return 1;
  }

  return 0;
}

function runSimulation() {
  const rounds = parseInt(document.querySelector("#attempts").value, 10);
  const doSwitch = document.querySelector("#switch").checked;

  let counter = 0;
  let wins = 0;

  while (counter < rounds) {
    const result = playGame(doSwitch);
    wins = wins + result;
    counter = counter + 1;
  }

  const resultText = document.querySelector("#result");
  resultText.innerText = `Out of ${rounds} rounds, you win ${wins} games!`;
}

function main() {
  const button = document.querySelector("button");
  button.addEventListener("click", runSimulation);
}

main();

External CSS

This Pen doesn't use any external CSS resources.

External JavaScript

This Pen doesn't use any external JavaScript resources.