Skip to content

Instantly share code, notes, and snippets.

@JanDW
Created Jan 17, 2021
Embed
What would you like to do?
function shuffleArray(arr) {
for (let i = arr.length - 1; i > 0; i--) {
const j = Math.floor(Math.random() * (i + 1));
[arr[i], arr[j]] = [arr[j], arr[i]];
}
}
const montyHall = (n) => {
let wins = 0;
let doors = ["goat", "goat", "car"];
let choice = [0, 1, 2];
for (let index = 0; index < n; index++) {
shuffleArray(doors);
shuffleArray(choice);
if (doors[choice[0]] != "car") {
wins++;
}
}
return wins;
};
let countWinArr = [];
for (let i = 0; i < 1000; i++) {
countWinArr[i] = montyHall(100);
}
const arrMin = (arr) => Math.min(...arr);
const arrMax = (arr) => Math.max(...arr);
const arrAvg = (arr) => arr.reduce((a, b) => a + b, 0) / arr.length;
const arrMed = (arr) => {
const mid = Math.floor(arr.length / 2),
nums = [...arr].sort((a, b) => a - b);
return arr.length % 2 !== 0 ? nums[mid] : (nums[mid - 1] + nums[mid]) / 2;
};
const countWinArrMin = arrMin(countWinArr);
const countWinArrMax = arrMax(countWinArr);
const countWinArrAvg = arrAvg(countWinArr);
const countWinArrMed = arrMed(countWinArr);
console.log({ countWinArrMin, countWinArrMax, countWinArrAvg, countWinArrMed, countWinArr });
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment