trying to iterate over an array to find two array items whose sum equals the target, not sure why isnt working
const numsArr = [2,7,11,15]
const numTarget = 9
const twoSum = function(nums, target) {
const first = 0;
const second = 0;
for(i=0; i<=nums.length; i++){
let tester = nums[i];
if(tester + nums[i] == target){
console.log('found it ')
}else{
console.log('i failed')
}
}
};
twoSum(numsArr, numsTarget)
You should always check for typo's: numTarget
is not numsTarget
; Furthermore, break
the loop if the desired result is reached. Try something like:
const numsArr = [2, 7, 11, 15];
const sumFromTarget = (nums, target) => {
let sum = 0;
for (let i = 0; i <= nums.length; i += 1) {
sum += nums[i];
// ^ add current value to sum
if (sum === target) {
console.log(nums.slice(0, i + 1).join(" + ") + " = " + target);
break;
// result is reached, no need for further processing
}
}
if (sum !== target) {
// ^ true if the loop is completed without result
console.log(`Could not reach ${
target} summing the consecutive values of the given array`);
}
}
sumFromTarget(numsArr, 9);
sumFromTarget(numsArr, 17);
sumFromTarget(numsArr, 20);
Now if you want to find a certain sum from any of the values in the array, you have to do a bit more work. Something like:
console.clear();
const numsArr = [2, 7, 11, 15];
const sumFromTarget = (nums, target) => {
let nums2 = nums.slice();
let resultValues = [];
for (let i = 0; i <= nums.length; i += 1) {
const x = nums2.reduce((acc, n, ni) => {
const runningTotal = ni > 0 ? acc[ni - 1][1] + n : n;
if (runningTotal === target) {
resultValues = nums2.slice(0, ni + 1);
}
if (n + nums[i] === target) {
resultValues = [nums[i], n];
}
return [...acc, [n + nums[i], runningTotal]];
}, []);
const check = x.find(n => n[0] === target || n[1] === target);
if (check) {
console.log(`found a solution (${resultValues.join(" + ")})`);
sum = target;
break;
}
}
if (!resultValues.length) {
console.log(`Could not reach ${
target} summing any of the values of the given array`);
}
}
sumFromTarget(numsArr, 9);
sumFromTarget(numsArr, 17);
sumFromTarget(numsArr, 13);
sumFromTarget(numsArr, 120);
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments