Created
August 2, 2017 00:40
-
-
Save BraedenYoung/b3174148c1f6fb743fe4ec0d5c7b793d to your computer and use it in GitHub Desktop.
Sum From Two Arrays
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
/* | |
* a: [1, 2, 3] | |
* b: [10, 20, 30, 40] | |
* v: 42 | |
*/ | |
function sumOfTwo(a, b, v) { | |
a = new Set(a); | |
return b.map((x) => { if (a.has(v - x)) return true;}).some((isValid) => {return isValid}); | |
} | |
// Failed on last hidden | |
function sumOfTwo2(a, b, v) { | |
aPointer = 0; | |
bPointer = 0; | |
/* | |
* Create a set of one to compare against the other. | |
* Sort both and have one in reverse so the index | |
* 'pointers' will just have to be decremented | |
*/ | |
a = [...new Set(a)].sort(function (a, b) { return a - b; }); | |
b.sort(function (a, b) { return a - b; }).reverse(); | |
// | |
while (true) { | |
sum = a[aPointer] + b[bPointer]; | |
if (sum === v) { | |
return true; | |
} else if (sum < v) { | |
aPointer += 1; | |
if (aPointer == a.length) { | |
aPointer -= 1; | |
bPointer -= 1; | |
if (bPointer < 0) return false; | |
} | |
} else { | |
bPointer += 1; | |
if (bPointer == b.length) { | |
bPointer -= 1; | |
aPointer -= 1; | |
if (aPointer < 0) return false; | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment