Pairwise driving me crazy! Please help!

Pairwise driving me crazy! Please help!
0.0 0

#1

The following is my code, can someone please tell me why it will not work for the following case at the bottom? It works well for the other test cases.

function pairwise(arr, arg) {
  
  var indexesToAdd = [ ];
  var total = 0;
  //The first loop below should go through each number in the array.
  for (var i = 0; i < arr.length; i++) {
    //now the inner loop will check if the adding to each number in array will equal arg. If it does, and the indexes do not match numbers that are already in the array, push both indexes to indexestoadd array.
    for (var j = 1; j < arr.length &&                      

indexesToAdd.indexOf(i) === -1 &&  

indexesToAdd.indexOf(j) === -1 ; j++) {
           if (arr[i] + arr[j] === arg) {
                if (indexesToAdd.indexOf(i) === -1) {
                     indexesToAdd.push(i);
                }
                if (indexesToAdd.indexOf(j) === -1) {
                     indexesToAdd.push(j);
                }
              }
            }
    
         }
  
  
  for (var y = 0; y < indexesToAdd.length; y++) {
    total += indexesToAdd[y];
  }
  
return total;
}

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

#2

can you indent your code?


#3

I tried to through my phone but I guess it didn’t work. :confused: I will do it on my computer tomorrow, Lord willing. Thanks for your response.


#4

This line:

for (var j = 1; j < arr.length && indexesToAdd.indexOf(i) === -1 &&  indexesToAdd.indexOf(j) === -1; j++)

If you have something in your indexesToAdd array your loop terminates.

[Details=Spoiler]

function pairwise(arr, arg) {

  if (!arr.length) return 0;

  var indexesToAdd = [];
  //The first loop below should go through each number in the array.
  for (let i = 0; i < arr.length; i++) {
    //now the inner loop will check if the adding to each number in array will equal arg.
    //If it does, and the indexes do not match numbers that are already in the array, push both indexes to indexestoadd array.
    for (let j = 0; j < arr.length; j++) {
      if (indexesToAdd.indexOf(i) === -1 && indexesToAdd.indexOf(j) === -1) {
        if (arr[i] + arr[j] === arg && i !== j) {
          indexesToAdd.push(i);
          indexesToAdd.push(j);
        }
      }
    }
  }
  return indexesToAdd.reduce((a, b) => a + b);
}

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

[/Details]


#5

Ahhhh that’s what I thought the problem was but I was not sure how to go about solving it! Thank you so much for your help! :smiley: