Using Recursion To Search All Combinations Of Elements In An Array Of Integers
I am working on this problem from Coderbyte using JS: Have the function ArrayAdditionI(arr) take the array of numbers stored in arr and return the string true if any combination of
Solution 1:
Your algorithm has a flaw. Your function looks only one step forward. You need to add loop inside to look over all rest values.
function ArrayAdditionI(arr) {
// sorting the array to easily remove the biggest value
// slice added to prevent original array modification
var sArr = arr.slice().sort(function (a, b) {
return a - b;
});
// removing the biggest value
var biggest = sArr.pop();
function recursion(start, i) {
var result = false;
// looking over all rest values of array
for (var j = i; j < sArr.length && !result; j++) {
if (sArr[j] + start === biggest) {
result = true;
}
else if (start + sArr[j] < biggest) {
result = recursion(start + sArr[j], j + 1);
}
}
return result;
}
return recursion(0, 0);
}
Solution 2:
function ArrayAdditionI (arr) {
var sArr = arr.sort(function (a,b) {
return a-b;
});
var biggest = sArr.pop();
function recursion (start, indx) {
if (start + sArr[indx] === biggest) {
return true;
}
else if (sArr.length < indx) {
return false;
}
else if (start + sArr[indx] < biggest) {
return recursion(start + sArr[indx], indx + 1) || recursion(start, indx+1)
}
else {
return false;
}
}
return recursion(0,0);
}
Post a Comment for "Using Recursion To Search All Combinations Of Elements In An Array Of Integers"