Skip to content

Instantly share code, notes, and snippets.

@dclowd9901
Last active August 29, 2015 14:19
Show Gist options
  • Save dclowd9901/efa6c4f37915b8f3794d to your computer and use it in GitHub Desktop.
Save dclowd9901/efa6c4f37915b8f3794d to your computer and use it in GitHub Desktop.
Pathfinder: Find all permutations of values that add up to a value
/**
* 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