Created
April 19, 2018 06:11
-
-
Save aioutecism/72e5794d9998500e6b4685f351660058 to your computer and use it in GitHub Desktop.
JavaScript version to the solution of Throwing Eggs from a Building problem. https://medium.freecodecamp.org/how-to-solve-the-google-recruiters-puzzle-about-throwing-eggs-from-a-building-de6e7ef1755d
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
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