Last active
January 29, 2020 15:23
-
-
Save Beraliv/e6ae633c8ac3e54bed38eda75ba4f583 to your computer and use it in GitHub Desktop.
Recursive to iterative algorithm change
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
export const decompose = (n: number) => { | |
const decomposeWithIndex = (rest: number, index: number, currentResult = []) => { | |
var repeat = true; | |
var saved = []; | |
while (repeat) { | |
repeat = false; | |
if (index < 0) { | |
if (saved.length > 0) { | |
const lastSaved = saved.pop(); | |
rest = lastSaved.rest; | |
currentResult = lastSaved.currentResult; | |
index = lastSaved.index; | |
repeat = true; | |
continue; | |
} | |
return null; | |
} | |
if (index * index > rest) { | |
index = index - 1; | |
repeat = true; | |
continue; | |
} | |
if (index * index === rest) { | |
return [index, ...currentResult]; | |
} | |
// index * index < rest | |
saved.push({ | |
rest, | |
index: index - 1, | |
currentResult, | |
}); | |
rest = rest - index * index; | |
currentResult = [index, ...currentResult]; | |
index = index - 1; | |
repeat = true; | |
} | |
} | |
return decomposeWithIndex(n * n, n - 1); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment