Skip to content

Instantly share code, notes, and snippets.

@aioutecism
Created April 19, 2018 06:11
Show Gist options
  • Save aioutecism/72e5794d9998500e6b4685f351660058 to your computer and use it in GitHub Desktop.
Save aioutecism/72e5794d9998500e6b4685f351660058 to your computer and use it in GitHub Desktop.
const bestNextStepCache = {};
function bestNextStep(floors) {
if (!bestNextStepCache[floors]){
if (floors <= 2) {
bestNextStepCache[floors] = 1;
}
else {
let min = Infinity;
let nextStep;
for (let i = 1; i <= floors; i++) {
const throws = maxThrows(floors, i);
if (throws < min) {
min = throws;
nextStep = i;
}
}
bestNextStepCache[floors] = nextStep;
}
}
return bestNextStepCache[floors];
}
function maxThrows(floors, next) {
if (floors <= 2) {
return floors;
}
else {
return Math.max(next, 1 + bestMaxThrows(floors - next));
}
}
const bestMaxThrowsCache = {};
function bestMaxThrows(floors) {
if (!bestMaxThrowsCache[floors]) {
bestMaxThrowsCache[floors] = maxThrows(floors, bestNextStep(floors));
}
return bestMaxThrowsCache[floors];
}
function findSteps(floors) {
const steps = [];
let accumulatedFloors = 0;
while (floors > 0) {
const nextStep = bestNextStep(floors);
accumulatedFloors += nextStep;
steps.push(accumulatedFloors);
floors = floors - nextStep;
}
return steps;
}
console.log(findSteps(100));
console.log(bestMaxThrows(100));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment