Skip to content

Instantly share code, notes, and snippets.

@abzeede
Last active July 22, 2019 03:55
Show Gist options
  • Save abzeede/0f032b543c9a4d036d3adfdfbd7bd43e to your computer and use it in GitHub Desktop.
Save abzeede/0f032b543c9a4d036d3adfdfbd7bd43e to your computer and use it in GitHub Desktop.
const availableSteps = [1, 4, 5]
function findTotalAvailablePath(prevStep, n) {
let totalPath = 0
availableSteps.map((step) => {
const nextStep = step + prevStep
if (nextStep === n) {
totalPath++
} else if (nextStep < n) {
totalPath += findTotalAvailablePath(nextStep, n)
}
})
return totalPath
}
const cacheF = {}
function findTotalAvailablePathM(prevStep, n) {
let totalPath = 0
availableSteps.map((step) => {
const nextStep = step + prevStep
if (nextStep === n) {
totalPath++
} else if (nextStep < n) {
if (typeof cacheF[nextStep] !== 'undefined') {
totalPath += cacheF[nextStep]
} else {
const avaiablePaths = findTotalAvailablePathM(nextStep, n)
totalPath += avaiablePaths
cacheF[nextStep] = avaiablePaths
}
}
})
return totalPath
}
console.log("Normal Recursion")
console.time("Time: ")
console.log("Total Possibility: ", findTotalAvailablePath(0, 40))
console.timeEnd("Time: ")
console.log("------------------------------------------")
console.log("Memorize Recursion")
console.time("Time: ")
console.log("Total Possibility: ", findTotalAvailablePathM(0, 40))
console.timeEnd("Time: ")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment