Algorithms: Pairwise - test failed, when result ok

My code returns expected result, however it doesn’t pass the test. Can anybody help me?

let pairs = []; // array of pairs
let used = []; // for index already used
let result = 0;
function pairwise(arr, arg) {
  // loop for all combination of paris sum
  for(let i = 0; i< arr.length; i++){
    for(let j = 0; j< arr.length; j++){
      if(i==j){ // exclude combination element with itself
        continue;
      }
      if((arr[i]+arr[j] == arg)){ // check if sum matches arg value
        if(used.includes(i) || used.includes(j)){ // if indexes already used -> continue
          continue;
        }else{ // if not push matched pair and used indexes
          used.push(i);
          used.push(j);
          pairs.push([i,j]);
        }
      }
    }
  }
  // Sum matched pairs in arrays, and sum all results
  for(let i =0; i<pairs.length;i++){
    result += pairs[i].reduce(getSum);
  }
  //console.log(result);
  return result;
}
function getSum(total, num) {
  return total + num;
}
pairwise([1, 4, 2, 3, 0, 5], 7);


You have used global variables. The tests may well work for you one at a time, in isolation, but you can easily see the issue if you just put that code into the browser console and just run the function over and over with different inputs:

pairwise([1, 4, 2, 3, 0, 5], 7)
11 // value of result started at 0
pairwise([1, 3, 2, 4], 4)
22  // value of result started at 11
pairwise([1, 1, 1], 2)
33 // value of result started at 22
pairwise([0, 0, 0, 0, 1, 1], 1)
48 // value of result started at 33
pairwise([], 100)
63 // value of result started at 48
2 Likes

Oh, now I see the problem. Thank you!

1 Like