Created
September 4, 2013 19:31
-
-
Save hackingbeauty/6441715 to your computer and use it in GitHub Desktop.
Find pairs that equal 100, remove duplicate pairs.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Array.prototype.sumPairs = function(){ | |
var arr = this, pairs = [], subPair, currentElem, compareElem; | |
for(var i = 0; i < arr.length; i++){ | |
currentElem = arr[i]; | |
for(var j = i+1; j<arr.length; j++){ | |
compareElem = arr[j]; | |
if((currentElem + compareElem) === 100){ | |
subPair = new Array(); | |
subPair.push(currentElem); | |
subPair.push(compareElem); | |
pairs.push(subPair.sort()); | |
} | |
} | |
} | |
return uniqPairs(pairs); | |
} | |
function uniqPairs(arr) { | |
var seen = {}; | |
return arr.filter(function(elem) { | |
var k = JSON.stringify(elem); | |
return (seen[k] === 1) ? 0 : seen[k] = 1; | |
}) | |
} | |
console.log([1,98,99].sumPairs()); | |
console.log([95,5,95].sumPairs()); | |
console.log([95,5,95,5].sumPairs()); | |
console.log([80,5,20,25,75,15,2,5,2,85].sumPairs()); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment