Well its a problem I found on codewar, and sharing it hear as stuck with it almost for a week and so close to solve this problem and really don’t want to give up now . Instruction for the problem is given below :
sum_pairs([11, 3, 7, 5], 10)
# ^--^ 3 + 7 = 10
== [3, 7]
`indent preformatted text by 4 spaces`
sum_pairs([4, 3, 2, 3, 4], 6)
# ^-----^ 4 + 2 = 6, indices: 0, 2 *
# ^-----^ 3 + 3 = 6, indices: 1, 3
# ^-----^ 2 + 4 = 6, indices: 2, 4
# * entire pair is earlier, and therefore is the correct answer
== [4, 2]
sum_pairs([0, 0, -2, 3], 2)
# there are no pairs of values that can be added to produce 2.
== None/nil/undefined (Based on the language)
sum_pairs([10, 5, 2, 3, 7, 5], 10)
# ^-----------^ 5 + 5 = 10, indices: 1, 5
# ^--^ 3 + 7 = 10, indices: 3, 4 *
# * entire pair is earlier, and therefore is the correct answer
== [3, 7]
NOTE: There will also be lists tested of lengths upwards of 10,000,000 elements. Be sure your code doesn’t time out.
Now, I solved the problem. But its timing out when it tested of lengths upwards of 10000000 elements. Its getting timed out. Here is my code
var sum_pairs = function(ints, s) {
//your code here
var film = [];
var pair = [];
for (var i = 0; i < ints.length; i++) {
holder = s - ints[i];
for (var j = 0; j < ints.length; j++) {
if (holder == ints[j] && i !== j && i - j > 0) {
var indices = i + j;
var distance = i - j;
film.push([distance, indices, [holder, ints[i]]]);
};
}
}
if (film.length == 0) {
return film[1];
} else {
pair = film.sort(function(a, b) {
return a[0] - b[0];
});
console.log(pair[0][2]);
return pair[0][2];
}
}
window.onload = function() {
l1 = [1, 4, 8, 7, 3, 15];
l2 = [1, -2, 3, 0, -6, 1];
l3 = [20, -13, 40];
l4 = [1, 2, 3, 4, 1, 0];
l5 = [10, 5, 2, 3, 7, 5];
l6 = [4, -2, 3, 3, 4];
l7 = [0, 2, 0];
l8 = [5, 9, 13, -3];
sum_pairs(l5, 10);
}
I know I am running a double loop which is the reason for time out. But don’t see any other appropriate way to get this done. Please don’t give me any straight answer; as I really don’t want to spoil it (like I already found one on stackoverflow but they just posting the answer directly there, so I skip the whole topic ) So waiting for your feedback.