I have completed an inefficient, but a working algorithm to figure out which pair of numbers in an array (arr1)
add up to the sum. I am facing these two problems:
(1) It is giving me "every" pair (e.g. 1+11 as well as 11+1 when the sum is 12),
AND
(2) I don't want it to add a number to itself (e.g. findArrSum([1, 3, 4, 8, 9, 11, 6, ], 12)
I do not want it to return (6+6)). I can make this ignore 6 through my if statement, but in that case it will also ignore the solution (6+6 in this example findArrSum([1, 3, 4, 8, 9, 11, 6, 6], 12)
.
function findArrSum(arr1, sum) {
var i = 0;
for (i in arr1) {
arr1.map(function(num) {
var answerSum = (num + arr1[i]);
if (answerSum == sum && num != arr1[i]) {
console.log(num +"+" +arr1[i] +"=" +sum);
}
});
}
}
console.log('Enter an array and a sum that you want a pair to add to: ')