Trouble with Arrays
Added 2 years ago, Modified 2 years ago, Under Web Applications
I spent some time with a friend trying to optimize a simple algorithm: Given an array of positive integers, extract two elements (values "a", and "b") for which its sum equals a control number "s". This looks much like an interview question, and my understanding is that this exercise is rather old, but here we go:

Problem: having the following array: [1,3,5,8,9,15], find out which two elements sum 17, Results should be: { a: 8, b: 9 }

Language: JavaScript

Part I, the un-optimized, brute force, and ugly code:

```/* So.. s = a + b (keep this in mind) */
function sum2(array, s) {
var arrLength = array.length,
arrIdx = 0,
a = 0,
b = 0,
controlArray = ,
ctrlArrIdx = 0;

/* Now Loop through the main array */
for (arrIdx = 0; arrIdx < arrLength; arrIdx++) {
/* Our "a" value will be the element of the
array, which we are currently in..
*/
a = array[arrIdx];
/* Loop through our "control" array */
for (ctrlArrIdx = 0;
ctrlArrIdx < controlArray.length;
ctrlArrIdx++) {
if (arrIdx === 0) {
b = -1;
} else {
/* Our "b" value is the value
of our "control" array..
*/
b = controlArray[ctrlArrIdx];
}
/* If the formula is true... Success */
if (b >= 0 && a + b === s) {
return { a: a, b: b };
} else {
/* No match yet, add the number
to our control array */
controlArray.push(num);
}
}
}
/* If all else fail */
}
console.log(sum2([1,3,5,8,9,15], 17));
```

Now the cool, thought out one..

```// s = a + b
// (therefore) a = s - b
function sum2(array, s) {
var ctrlArray =[],
a = 0,
b = 0,

for (var i = 0; i < array.length; i++) {
/* Get out "known" "b" value from
the main array
*/
b = array[i];
/* Apply formula, now we now what value
"a" we need!
*/
var a = s - b;
/* if value of "a" is found, then we're
set!, otherwise temporarily store so
we can scan it on our next interaction
*/
if (ctrlArray.indexOf(a) >= 0) {
results = {a: a, b: b};
break;
} else {
ctrlArray.push(b);
}
}
return results;
}

console.log(sum2([1,3,5,8,9,15], 17));
```

It took me a bit of time to figure out why a second loop is not necessary needed, and also why sorting the array is also not necessarily needed, much cleaner code, and easier to understand. Hope it helps you folks.