Challenge:
Given an array arr
, find element pairs whose sum equal the second argument arg and return the sum of their indices.
If multiple pairs, that have the same numeric elements but different indices are possible, return the smallest sum of indices. Once an element has been used, it cannot be reused to pair with another.
For example pairwise([7, 9, 11, 13, 15], 20)
returns 6
.
My code (works, passes all validations) is the below:
function pairwise(list, sum) {
// noprotect
var innerCounter,
outerCounter,
used = {},
returnValue = 0;
for( outerCounter = 0 ; outerCounter < list.length-1 ; outerCounter++){
if( used[outerCounter] )
continue;
for( innerCounter = outerCounter+1 ; innerCounter < list.length ; innerCounter++){
if( used[innerCounter] )
continue;
if( list[innerCounter] + list[outerCounter] == sum ){
used[innerCounter] = true;
returnValue = returnValue + innerCounter + outerCounter;
break;
}
}
}
return returnValue;
}
I had some internal debate on sum
as a parameter name, since we also return a sum. But I stuck to returnValue
for the return value and sum
for the parameter. Any feedback on this is welcome, from style to algorithm.
list
necessarily distinct? \$\endgroup\$