Pairwise: Trouble getting through all tests

Pairwise: Trouble getting through all tests
0

#1

Tell us what’s happening:
This is my code. I am not going through two tests.Probably I stuck at the sentence " Each pair should use the lowest possible available indices. Once an element has been used it cannot be reused to pair with another element." Need help to get through this.

Your code so far


function pairwise(arr, arg) {
  let nArr = [];
  for (let i = 0; i < arr.length; i++) {
    for (let j = 0; j < arr.length; j++) {
      if (arr[i] + arr[j] == arg) {
        if (i != j) {
          nArr.push([arr[i], arr[j]]);
        }
      }
    }
  }
  console.log(nArr);
  let result, fResult = 0;
  for (let k = 0; k < nArr.length; k++) {
    result = arr.indexOf(nArr[k][0]) + arr.indexOf(nArr[k][1]);
    fResult += result;
  }
  console.log(fResult);
  return fResult/2;

}

pairwise([0, 0, 0, 0, 1, 1], 1);

Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.100 Safari/537.36.

Link to the challenge:
https://learn.freecodecamp.org/coding-interview-prep/algorithms/pairwise


#2

@Bhagathp,

you have the right approach with your solution, but you are missing a few things.

Take a look at the for loops you have in the beginning of your code. They are both running from the same index. The goal of the exercise is to find two distinct pairs and not use the same index twice.

You can move the if clause that checks this higher up in your code to save computations.

Furthermore, you are not marking indices that you have already used. Meaning, what makes your for loops identify which indices have already been used?

Focus on that point and you will solve this exercise.

Good luck


#3

Thank you @TomerPacific :grinning: ,

Yes, I have taken your suggestions and re-written my code, It worked out.

I have changed the starting point of second loop, so that both loops doesn’t start from same.

And to avoid reusing of used indices, I have assigned NaN to them. (Point taken from exercise hints)

Finally, I have added the indices. It worked out.


#4

@Bhagathp,
great job! Way to go :+1: