Last active
September 9, 2015 13:30
-
-
Save gor181/59c0825fb3e1ee4a4b51 to your computer and use it in GitHub Desktop.
Given an array of positive integers, write a function which returns all the unique pairs which add (equal) up to 100.
This file contains hidden or 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
/* | |
Coding | |
Given an array of positive integers, write a function which returns all the unique pairs which add (equal) up to 100. | |
sample_input = [0, 1, 100, 99, 0, 10, 90, 30, 55, 33, 55, 75, 50, 51, 49, 50, 51, 49, 51] | |
sample_output = [[1,99], [0,100], [10,90], [51,49], [50,50]] | |
*/ | |
var sample_input = [0, 1, 100, 99, 0, 10, 90, 30, 55, 33, 55, 75, 50, 51, 49, 50, 51, 49, 51]; | |
var result = getNumbersOf(100, sample_input, true, []); | |
function getNumbersOf(targetNum, numbers, unique, res) { | |
var number = numbers.shift(); | |
if (!numbers.length) { | |
return res; | |
} | |
for (var i = 0; i < numbers.length; i++) { | |
if ((number + numbers[i]) === targetNum) { | |
var result = [number, numbers[i]]; | |
if (unique) { | |
if (JSON.stringify(res).indexOf(JSON.stringify(result)) < 0) { | |
res.push(result); | |
} | |
} else { | |
res.push(result); | |
} | |
numbers.splice(numbers.indexOf(numbers[i]), 1); | |
break; | |
} | |
} | |
return getNumbersOf(targetNum, numbers, unique, res); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment