Charger probability simulator
Suppose you think you're 80% likely to have left your laptop power adapter somewhere inside a case with 4 otherwise-identical compartments. You check 3 compartments without finding your adapter. What's the probability that the adapter is inside the remaining compartment?
by ubershmekel
HTML
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>JS Bin</title>
</head>
<body>
<a href="https://twitter.com/ESYudkowsky/status/1455930656991559681">https://twitter.com/ESYudkowsky/status/1455930656991559681</a>
<p>Suppose you think you're 80% likely to have left your laptop power adapter somewhere inside a case with 4 otherwise-identical compartments. You check 3 compartments without finding your adapter. What's the probability that the adapter is inside the remaining compartment?
</p>
<div id="log">
</div>
</body>
</html>
JavaScript
// Utils
let range = n => [...Array(n).keys()]
function trim(str, ch) {
var start = 0,
end = str.length;
while (start < end && str[start] === ch)
++start;
while (end > start && str[end - 1] === ch)
--end;
return (start > 0 || end < str.length) ? str.substring(start, end) : str;
}
const logEl = document.getElementById('log');
function log(text) {
const newLineEl = document.createElement("p");
newLineEl.innerHTML = trim(JSON.stringify(text), '"');
logEl.prepend(newLineEl);
}
// Solve
log("starting calculation " + Math.random());
const bagCompartmentCount = 4;
const probabilityInBag = 0.8;
function placeLaptop() {
// 0 - 3 = case compartments
// 4 = not in case
const seed = Math.random();
if (seed < probabilityInBag) {
// 0 - 3
return Math.floor(Math.random() * bagCompartmentCount);
} else {
return bagCompartmentCount;
}
}
function popRandom(arr) {
const selectedIndex = Math.floor(Math.random() * arr.length);
const selectedValue = arr[selectedIndex];
arr.splice(selectedIndex, 1);
return {
selectedValue,
selectedIndex,
}
}
let inBag = 0;
let outOfBag = 0;
function guess(placed) {
const compartmentsLeft = range(bagCompartmentCount);
let turns = 1;
while (compartmentsLeft.length > 1) {
const result = popRandom(compartmentsLeft);
if (result.selectedValue === placed) {
log(`found after ${turns}`)
return;
}
turns++;
if (turns > 100) {
// should be impossible
log('gave up');
break;
}
}
log("only one compartment left to check");
if (compartmentsLeft[0] === placed) {
inBag++;
} else {
outOfBag++;
}
// log("1")
}
for (let i = 0; i < 5000; i++) {
guess(placeLaptop())
}
log(`inBag ${inBag}`);
log(`outOfBag ${outOfBag}`);
log(`probability in last compartment ${inBag / (inBag + outOfBag)}`)