Created
February 14, 2020 17:23
-
-
Save uhop/32983dad7f54fd58cc462405b15be65f to your computer and use it in GitHub Desktop.
How many tries it takes to roll a particular sequence
This file contains 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
'use strict'; | |
const roll = pattern => { | |
const samples = []; | |
let counter = 0; | |
for(;;){ | |
if (samples.length >= pattern.length) { | |
samples.shift(); | |
} | |
const sample = Math.floor(Math.random() * 6) + 1; | |
samples.push(sample); | |
++counter; | |
compare: if (samples.length >= pattern.length) { | |
for(let i = 0; i < pattern.length; ++i) { | |
if (pattern[i] !== samples[i]) break compare; | |
} | |
break; | |
} | |
} | |
return counter; // we got our sequence | |
}; | |
const time = (pattern, n = 1000000) => { | |
const start = Date.now(); | |
let averageRolls = 0; | |
for (let i = 0; i < n; ++i) { | |
const rolls = roll(pattern); | |
averageRolls += rolls / n; | |
} | |
const duration = Date.now() - start; | |
console.log(`${n} trials in ${duration / 1000}s looking for [${pattern.join(', ')}]`); | |
console.log(`Average number of rolls: ${averageRolls}`); | |
}; | |
time([4, 5, 6]); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment