Professional Documents
Culture Documents
Pairwise
Pairwise
// 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;
});
return res;
}
pairwise([1,4,2,3,0,5], 7);