Public
Edited
May 25, 2023
Insert cell
Insert cell
chart = PieChart(results, {
name: d => d.name,
value: d => d.wins,
width,
height: 300
})
Insert cell
results = simulate()
Insert cell
function simulate() {
const n = 10000;
const results = [{ name: 'stay', wins: 0 }, { name: 'switch', wins: 0 }];
for (let i = 0; i < n; i++) {
const doors = initDoors();
const choice = contestantInitialChoice();
const removed = removeGoat(doors, choice);
if (isWin(removed.doors, removed.contestantChoice)) {
results[0].wins++;
} else {
results[1].wins++;
}
}
return results;
}
Insert cell
function initDoors() {
const doors = ['goat', 'goat', 'goat'];
doors[rndIdx()] = 'car';
return doors;
}
Insert cell
removeGoat(['goat', 'goat', 'car'], 0)
Insert cell
function isWin(doors, contestantChoice) {
return doors[contestantChoice] === 'car';
}
Insert cell
function removeGoat(doors, contestantChoice) {
const possibleIndices = doors.filter((_, i) => i !== contestantChoice && doors[i] === 'goat').map((_, i) => i);
const indexToRemove = possibleIndices[rndIdx(possibleIndices.length)];
const shiftedContestantChoice = contestantChoice > indexToRemove ? contestantChoice - 1 : contestantChoice;
return {
doors: doors.filter((_, i) => i !== indexToRemove),
contestantChoice: shiftedContestantChoice
}
}
Insert cell
function contestantInitialChoice() {
return rndIdx();
}
Insert cell
function rndIdx(upperBound = 3) {
return Math.floor(Math.random() * upperBound);
}
Insert cell
import {PieChart} from "@d3/pie-chart"
Insert cell

Purpose-built for displays of data

Observable is your go-to platform for exploring data and creating expressive data visualizations. Use reactive JavaScript notebooks for prototyping and a collaborative canvas for visual data exploration and dashboard creation.
Learn more