Skip to content

Instantly share code, notes, and snippets.

@uhop
Created February 14, 2020 17:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save uhop/32983dad7f54fd58cc462405b15be65f to your computer and use it in GitHub Desktop.
Save uhop/32983dad7f54fd58cc462405b15be65f to your computer and use it in GitHub Desktop.
How many tries it takes to roll a particular sequence
'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