Home > Enterprise >  Adding Negative Integers in Javascript
Adding Negative Integers in Javascript

Time:07-21

I am trying to write a function that returns the first two values in order of appearance that add to the sum. My function works fine with positive numbers, but not with negative. Can anyone tell me what I am doing wrong?

This function return an empty array:

const sumOfPairs = (arr, sum) => {
  const answer = [];
  for (let i = 0; i < arr.length; i  ) {
    for (let j = 0; j < arr.length; j  ) {
      if (arr[i]   arr[j] === sum && i != j) {
        answer.push(arr[j], arr[i]);
      }
      break;
    }
  }
  return answer;
}

console.log(sumOfPairs([1, -2, 3, 0, -6, 1], -6));

CodePudding user response:

Your implementation doesn't work for all positive numbers either. Try 3 as sum.

I believe you want to put the break statement inside the if statement or just replace the body of the if statement with return [arr[j], arr[i]]:

const sumOfPairs = (arr, sum) => {
  for (let i = 0; i < arr.length; i  ) {
    for (let j = 0; j < arr.length; j  ) {
      if (arr[i]   arr[j] === sum && i != j) {
        // You can return here if you only want to find *one* pair
        // You also need add some additional logic if you want them
        // to be in the same order as in the original array:
        return i < j ? [arr[i], arr[j]] : [arr[j], arr[i]]
      }
    }
  }
  return []
}

console.log(sumOfPairs([1, -2, 3, 0, -6, 1], -6));

The current location of the break statement in your loop causes the inner loop to terminate after its first iteration! Therefore the inner loop is equivalent to testing whether the sum of the current outer loop's item (arr[i]) and 1 (the first element in the array) is equal the provided sum.

  • Related