Skip to content

Instantly share code, notes, and snippets.

@wsams
Last active August 29, 2015 14:16
Show Gist options
  • Save wsams/75dce5b06ce7cf11ff3b to your computer and use it in GitHub Desktop.
Save wsams/75dce5b06ce7cf11ff3b to your computer and use it in GitHub Desktop.
I enjoy the game King of Thieves and one aspect I'm always trying to improve is picking the locks. I know I can't cheat probability but it sure is fun trying. You have X amount of locks and you try opening them one-by-one. My current strategy is to just start from the first lock and work my way through to the end. The following JavaScript will a…
(function() {
var numLocks = 8;
var iterations = 1000;
function random(min, max) {
"use strict";
return Math.round(Math.random() * (max - min) + min);
}
function buildLocksArray() {
"use strict";
var locks = [];
var r = random(0, numLocks-1);
for (var i=0; i<numLocks; i++) {
if (i === r) {
locks.push('y');
} else {
locks.push('n');
}
}
return locks;
}
function buildRandomGuessOrder() {
var chosen = [];
var guessOrder = [];
for (var i=0; i<numLocks; i++) {
var r = random(0, numLocks-1);
while (chosen.indexOf(r) > -1) {
r = random(0, numLocks-1);
}
guessOrder.push(r);
chosen.push(r);
}
return guessOrder;
}
function guess(guessRandom, guessOrder) {
var guesses = [];
for (var i=0; i<iterations; i++) {
var locksArray = buildLocksArray();
var c = 1;
if (guessRandom) {
guessOrder = buildRandomGuessOrder();
}
for (var k in guessOrder) {
if (locksArray[guessOrder[k]] === 'y') {
guesses.push(c);
break;
}
c++;
}
}
return guesses;
}
print(Math.round(guess(false, [0, 1, 2, 3, 4, 5, 6, 7])
.reduce(function(x, y) { return x + y; }) / iterations));
print(Math.round(guess(false, [0, 1, 2, 7, 3, 4, 5, 6])
.reduce(function(x, y) { return x + y; }) / iterations));
print(Math.round(guess(true)
.reduce(function(x, y) { return x + y; }) / iterations));
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment