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:
https://www.freecodecamp.org/challenges/pairwise