Pairwise help needed

Pairwise help needed
0

#1

Hello everyone!
I’m a bit confused (again) with the request for this last challenge in the algorithm series.

Here is my code so far (and my confusion below it):

function pairwise(arr, arg) {
  if (arr.length <1) {
    console.log(0)
    return 0
  }
  var sum = []
  for (var i = 0; i < arr.length; i++) {
    for (var j = 0; j < arr.length; j++) {
      if (parseInt(arr[i]+arr[j]) === arg) {
        console.log(arr[i] + ' + ' + arr[j] + ' = ' + parseInt(arr[i]+arr[j])) // just for me to check
        sum.push(i+j) // calculates the sum of the indexes
        arr.splice(i,1) // remove that element from the array so it cannot be used again AND
        arr.splice(i,0,undefined) // insert something so that the index does not move
      }
    }
  }
  console.log(sum)
  
  var result = sum.reduce(function (sum, element) {
    return sum + element
  })
  console.log('Sum of indices is: ',result)
  return result
}

This validates the 1st and last check of the exercise, and my confusion comes with understanding the requirement so:

If multiple pairs are possible that have the same numeric elements but different indices

By this I understand this scenario: pairwise([0, 0, 0, 0, 1, 1], 1)

where the pairs that sum 1 are: [ [ 0, 1 ], [ 0, 1 ], [ 0, 1 ], [ 0, 1 ] ]

and their respective indexes are: [ [ 0, 4 ], [ 1, 4 ], [ 2, 4 ], [ 3, 4 ] ]

because:

Once an element has been used, it cannot be reused to pair with another

We have to:

return the smallest sum of indices.

But I don’t understand how can one get 10 as the smallest sum of [ [ 0, 4 ], [ 1, 4 ], [ 2, 4 ], [ 3, 4 ] ]

What am I getting so wrong?

Thank you so much in advance,
Alex

Link to the challenge:


#2

This is a confusing challenge for sure.

A few things:

You are reusing the same element (the 1 at index 4). Recall that “Once an element has been used, it cannot be reused to pair with another”. There are two 1s and four 0s, so we will have two pairs that each sum to 1. We therefore want to take to two lowest-indexed 0s and match them with the two 1s.
0+ 1 = 1 → Indices 0 + 4 = 4
0 + 1 = 1 → Indices 1 + 5 = 6
4 + 6 = 10 → Return 10


#3

Thank you @ArielLeslie - it’s clear I was not thinking straight …arrg.

I’ll try again.
Thanks once again for your time.
Alex


#4

It’s a tricky challenge for sure. I had to read the description and walk through the example a couple times to get exactly what they were asking for. Happy coding!