Last active
August 29, 2015 14:19
-
-
Save dclowd9901/efa6c4f37915b8f3794d to your computer and use it in GitHub Desktop.
Pathfinder: Find all permutations of values that add up to a value
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
/** | |
* first - the starting values | |
* total - the value you want all values to add to | |
* optimal - the preferred final value of the sequence | |
* | |
* returns false if no path can be found to the answer | |
*/ | |
function pathfinder(first, total, optimal) { | |
var start = first - 1, | |
end = first + 1, | |
leftover, | |
result, | |
nextArr = []; | |
for (; start <= end; start++) { | |
if (start > 0) { | |
leftover = total - start; | |
if (leftover > 0) { | |
result = pathfinder(start, leftover, optimal); | |
} else if (leftover === 0 && optimal === start) { | |
result = true; | |
} else { | |
result = false; | |
} | |
if (result) { | |
nextArr.push({ | |
value: start, | |
next: result | |
}); | |
} | |
} | |
} | |
if (nextArr.length) { | |
return nextArr; | |
} else { | |
return false; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment