@dracoin My code was behaving erratically, and returning NaNs etc. Then I looked at your code and initialized searchVal, and for some reason, this fixed the problem…strange…? My code was exactly the same as yours, except for 1 thing - at first I didn’t bother to initialize searchValue, and instead just used arg - arr[element] inside the if statement. Anyway, here’s the code which failed…in case anyone wants to see indexes behaving erratically, inexplicably, which is what this scripting challenge is about…
function pairwise(arr, arg) {
var sumOfIdx = 0;
for (var i = 0; i < arr.length; i++) {
if (arr.indexOf(arg - arr[i]) !== -1 && arr.indexOf(arg - arr[i]) !== i) { //i.e. the ith element has at least 1 pair
sumOfIdx += i + arr.indexOf(arg - arr[i]);
arr[i] = "-";
arr[arr.indexOf(arg - arr[i])] = "-";
}
}
return sumOfIdx;
}
I don’t understand why pairwise([0, 0, 0, 0, 1, 1], 1) should return 10. The rules state that if “multiple pairs are possible that have the same numeric elements but different indices, return the smallest sum of indices.” None of the solutions above seem to be taking that rule into account.
Maybe I’m misinterpreting the rule?
0 0 0 0 1 1 // values
0 1 2 3 4 5 // indices
0 1 //= 4 * wouldn't this be the pair with the smallest sum of indices?
0 1 //= 5
0 1 //= 6
0 1 //= 7
0 1 //= 5
0 1 //= 6
0 1 //= 7
0 1 //= 8
This is exactly the same answer I got! This one was fun.
function pairwise(arr, arg) {
return arr.reduce((acc, num, i, a) => {
let z = a.indexOf((arg-num), i+1)
return z > 0 ? (a[z] = NaN, acc + i + z) : acc
}, 0)
}
Is a good practice to use a copy of the arguments instead of modify it directly, like in the advanced solution? And if the arr.indexOf() is a slowest method than the normal for loop in which cases it is preferable to use it?