Skip to content

Instantly share code, notes, and snippets.

@aldraco
Created February 28, 2015 16:58
Show Gist options
  • Save aldraco/7359b92f203a59900cc9 to your computer and use it in GitHub Desktop.
Save aldraco/7359b92f203a59900cc9 to your computer and use it in GitHub Desktop.
Pairwise bonfire FCC - very ugly solution
function pairwise(arr, arg) {
var indexRef = [];
var pushIndex;
// go through the arr
for (var i = 0; i < arr.length; i ++) {
// if that index is not already in indexRef, continue
if (indexRef.indexOf(i) < 0) {
// for that element, find its pair (arr.indexOf)
pushIndex = arr.indexOf(arg-arr[i]);
if (i !== arr.lastIndexOf(arg-arr[i])) {
if ((pushIndex >= 0) && (indexRef.indexOf(pushIndex) <0)) {
// if it exists,
// push those indexes to indexRef
indexRef.push(pushIndex);
indexRef.push(i);
arr[i] = -1;
arr[pushIndex] = -1;
}
}
}
// else, continue (nothing)
}
if (indexRef.length === 0) {
return 0;
}
var sum = indexRef.reduce(function(a,b) {
return a+b;
});
return sum;
}
pairwise([1,3,2,4], 4);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment