Skip to content

Instantly share code, notes, and snippets.

@gor181
Last active September 9, 2015 13:30
Show Gist options
  • Save gor181/59c0825fb3e1ee4a4b51 to your computer and use it in GitHub Desktop.
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.
/*
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