Pairwise return smaller value

Pairwise return smaller value
0

#1

Tell us what’s happening:
pairwise([0, 0, 0, 0, 1, 1], 1) should return 10
Can anyone explain this result? I thought 0 and 1 can only be used once, so the answer is 4.

Your code so far

function pairwise(arr, arg) {
  
  var ind = 0;
  var indArr = [];
  for(var i = 0; i < arr.length; i++){
    for(var j = 0; j < arr.length; j++){
      if(i < j && arr[i] + arr[j] == arg && indArr.indexOf(arr[i]) < 0){
        
        indArr.push(arr[i]);
        indArr.push(arr[j]);
        
        ind += (i + j);
      }
    }
  }
  return ind;
}

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

Your browser information:

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

Link to the challenge:


#2

The same 0 and 1 can only be used once.


#3

If multiple pairs are possible that have the same numeric elements but different indices, return the smallest sum of indices. Once an element has been used, it cannot be reused to pair with another.

my understanding is that 0 and 1 can only be used once and the smallest indices should be used. There is only one pair (0 and 1). the smallest indices for 0 is 0, for 1 is 4. so the result should be 4. How come it is 10?


#4

It says an element and not a number. In the test case of:

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

the pairing would look like:


#5

Ok, I got you. Thank you so much!


#6

Hey @randelldawson,

I am still not convinced. The question mentions that…

If multiple pairs are possible that have the same numeric elements but different indices, return the smallest sum of indices.

… which in my opinion means that the pair [0, 1] with indices [0, 4] prevails when compared with the pair [0, 1] with indices [1, 5], meaning the final result should be 4 instead of 10, don’t you think?

Cheers,
Fm


#7

This is the part you are not getting. Because there are more than one pair of 0, 1 which sum to 1, we return the smallest sum of indices. Since there are four indices, you must sum all of them. If the challenge would have wanted you to only use the first pair of 0,1 (indices 0 and 4 respectively), there would have been no reason to even discuss what to do when multiple pairs exist. The instructions would have just said return the sum of the indices for the first pair encountered. In my opinion, the fact the instructions describe what to do when multiple pairs exist, proves the need to sum the indices for all pairs.

Trust me, when I first worked on this challenge, I asked the same question.