You are on page 1of 2

function pairwise(arr, arg) {

// no pairs exist
if (arr.length < 2) return 0;
var max = Math.max.apply(Math,arr);
// impossible to get the desired sum
if (arg > 2*max) return 0;
// replace duplicates with null unless they are half of the desired sum.
// in that case keep a pair
var half = true;
//to help count the duplicate if it is half the desired sum
arr = arr.map(function(ele,idx,array){
if (idx=== 0) return ele;
if ( array.slice(0,idx).indexOf(ele) >= 0){
// a duplicate
if (2*ele === arg && half){
half = false; // keep no more duplicates
return ele;
}
else return null;
}
else return ele;
});

var len = arr.length;


var res = 0;
for (var sum = 1; sum < 2*len -2; sum++){
// (2*len -2) - 1 = indice_max + indice_max - 1 is
// the maximum of the sum of two different indices
for (var i = 0; i < len; i++){
for (var j = 0; j < i; j ++){
if (arr[i] !== null && arr[j] !== null) {
if ( arr[i] + arr[j] === arg && i + j === sum){
res += sum;
}
}
}
}
}

return res;

}
pairwise([1,4,2,3,0,5], 7);

You might also like