Dhruv Sharma
Dhruv Sharma

Reputation: 3

Why these two loops return different results?

Problem statement

Given an array arr, find element pairs whose sum equal the second argument arg and return the sum of their indices.

Disclaimer, I am not asking for the solution of this problem statement, but about the confusion between the following two loops I tried creating, whose functionality is almost exactly similar but consoling different outputs.

  1. First Loop
function pairwise(arr, arg) {
  const indexOfPair = []
  for ( let i = 0; i < arr.length -1; i++){
    for (let j = i + 1; j < arr.length -1; j++ ){
      let sum = arr[i] + arr[j]
      if ( sum === arg){
        indexOfPair.push(arr.indexOf(arr[i]), arr.indexOf(arr[j]))
        
      }
      else {
        continue
      }
    }
  }

console.log(indexOfPair)
console.log(indexOfPair.reduce((a, b) => a + b, 0))
}

pairwise([1,4,2,3,0,5], 7);

Console Output:[1,3] & 4

  1. Second Loop
function pairwise(arr, arg) {
  const indexOfPair = []

  for ( let i = arr.length - 1; i >= 0 ; i--){
    for (let j = i -1; j >= 0; j--){
      let sum = arr[i] + arr[j]
      if ( sum === arg){
        indexOfPair.push(arr.indexOf(arr[i]), arr.indexOf(arr[j]))
      }

    }
  }

  console.log(indexOfPair)
  console.log(indexOfPair.reduce((a, b) => a + b, 0))


}

pairwise([1,4,2,3,0,5], 7);

Console output: [5,2,3,1] & 11 -> This is the expected output and I am not getting why these two loops are returning different outcomes.

Upvotes: 0

Views: 84

Answers (1)

G-Paz
G-Paz

Reputation: 26

You're not getting to the last entry in arr.

  for ( let i = 0; i < arr.length - 1; i++){
    for (let j = i + 1; j < arr.length - 1; j++ )

should be

  for ( let i = 0; i <= arr.length - 1; i++){
    for (let j = i + 1; j <= arr.length - 1; j++ )

Upvotes: 1

Related Questions