Last active
September 4, 2022 11:04
-
-
Save roshnet/b2da88b153188da3b6bcbf4945e3aa64 to your computer and use it in GitHub Desktop.
A Node.js script for Veritasium's riddle (youtu.be/iSNsgj1OCLA)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const N = 100 | |
const TO_FIND = 42 | |
const BOXES = {} | |
let iterations = 0 | |
const trail = [] | |
/** | |
* @description Return a fresh set of slips on each call. | |
*/ | |
const generateSlips = () => new Array(N).fill().map((_, idx) => ++idx) | |
/** | |
* @description Assign random ID and remove it from `SLIPS`. | |
*/ | |
function extractRandomSlip() { | |
let randomSlip | |
while (true) { | |
randomSlip = Math.ceil(Math.random() * N) | |
if (SLIPS.includes(randomSlip)) | |
return SLIPS.splice(SLIPS.indexOf(randomSlip), 1) | |
else continue | |
} | |
} | |
/** | |
* @description Recurse to find the desired slip. | |
*/ | |
function findNext(key, depth = 1) { | |
trail.push(key) | |
iterations += 1 | |
if (BOXES[key][0] === 42) return key | |
const foundIn = findNext(BOXES[key], depth + 1) | |
if (depth > 1) return foundIn | |
return { | |
iterations, | |
trail, | |
foundIn, | |
} | |
} | |
const SLIPS = generateSlips() | |
for (let i = 1; i <= 100; i++) BOXES[i] = extractRandomSlip() | |
const result = findNext(TO_FIND) | |
console.log('Found in box #%d', result.foundIn[0]) | |
console.log('Took %s hops', result.iterations) | |
console.log(result.trail.join(' -> ')) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment