Algoritms: pairwise. Question about the hint page

Challenge

Hint page

I don’t get it, why the solution from guides uses array to collect indices, and then reduces it to get the result.

Our task is to find number, sum of indices.

So we can declare accumulator variable, and gather result with some += lines.

Also I am not a fan of using includes here, I think it’s unnecessary.

I would like to get feedback on these thoughts and also suggest alternative solution:

function pairwise(arr, arg) {
    //result accumulator
    let sumOfIndices = 0;
    //to track already used elems
    let isNotUsed = arr.map(elem => true)
    for (let i = 0; i < arr.length - 1; i++) {
      if (isNotUsed[i]) {
        for (let j = i + 1; j < arr.length; j++) {
          if (isNotUsed[j] === true && 
              arr[i] + arr[j] === arg) {
            sumOfIndices += (i + j);
            isNotUsed[i] = false;
            isNotUsed[j] = false;
            break;
          }
        }
      }
    }
    return sumOfIndices;
  }
  
  pairwise([1,4,2,3,0,5], 7);

I would get rid of the nested loop altogether, personally.

You’re basically replicating the effect of includes with a slightly bigger data structure here. Your solution and the first guide solution are basically the same in terms of logic.

1 Like

Ok, I see new solution on the hints page, with single loop. Need some time to provide specific questions about it.

I’d put that solution in the ‘clever trick’ category. It is one of those handy techniques that you can jump to once you have seen it a couple of times, but its not something that’s super common to need.

1 Like

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.