Let's say I have a set number like 9 and an array that has #s [1,2,4,6,3,9]
. I was wondering what would be the best approach to loop through and see if one or more of those #s can add up to 9. My initial thought was to:
- Check if the current array index value is equal to the magicNum
- If the current number is less than the magicNum, add it together with another number in the array and keep looping to see if it's a match
- If the above didn't work, move to the next number and repeat.
I have the first check fine but it's the other two I'm having trouble with. I know for starters that a recursive function may (or may not) be needed in addition to using reduce. Algorithms aren't my strong suit (yet) but I'm eager and more than willing to improve. Any type of guidance would be greatly appreciated.
const magicNum = 9;
const arr = [10,1,2,4,6,3];
for (let i = 0, arrLength = arr.length; i < arrLength; i++) {
if (arr[i] === magicNum) {
console.log('Number Found!');
continue;
} else if (arr[i] > magicNum) {
continue;
} else if (arr[i] < magicNum) {
// Stuck here
}
}