Skip to content

Commit f4d3f95

Browse files
committed
Merge pull request blakeembrey#143 from stezu/master
Add tests for array pair sum and a working solution.
2 parents de315a5 + 5b6b5ad commit f4d3f95

File tree

2 files changed

+21
-16
lines changed

2 files changed

+21
-16
lines changed
Lines changed: 9 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -1,20 +1,13 @@
1-
module.exports = function (k, array) {
2-
var hash = {},
3-
pairs = [];
1+
module.exports = function (sum, array) {
2+
var results = [];
43

5-
// Loop through the array once, storing the results in an object for a
6-
// time complexity of O(n) - the naive solution consists of two for loops
7-
// which results in a complexity of O(n^2)
8-
array.forEach(function (number) {
9-
// Make sure the value in unused and it's a unique pair
10-
if (hash[k - number] === false && k - number !== number) {
11-
pairs.push([number, k - number]);
12-
hash[k - number] = true; // Set it to "used"
4+
for (var i = 0, len = array.length; i < len; i++) {
5+
for (var j = i + 1; j < len; j++) {
6+
if (array[i] + array[j] === sum) {
7+
results.push([array[i], array[j]]);
8+
}
139
}
10+
}
1411

15-
// If the hash value is not true, set the hash to "unused"
16-
!hash[k - number] && (hash[number] = false);
17-
});
18-
19-
return pairs;
12+
return results;
2013
};

tests/javascript/array-pair-sum.js

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
var expect = require('chai').expect;
2+
var arrayPairSum = require('../../solutions/javascript/array-pair-sum');
3+
4+
describe('Array Pair Sum', function () {
5+
it('should find pairs that equal the expected sum', function () {
6+
expect(arrayPairSum(10, [3, 4, 5, 6, 7])).to.eql([[3, 7], [4, 6]]);
7+
});
8+
9+
it('should allow for duplicate results', function () {
10+
expect(arrayPairSum(8, [3, 4, 5, 4, 4])).to.eql([[3, 5], [4, 4], [4, 4], [4, 4]]);
11+
});
12+
});

0 commit comments

Comments
 (0)