Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit e7f1166

Browse files
Merge pull request knaxus#19 from mattstates/master
Unit tests & fix for "find-2-nums-adding-to-n"
2 parents 9a09f90 + a5e240f commit e7f1166

File tree

3 files changed

+72
-15
lines changed

3 files changed

+72
-15
lines changed

‎package-lock.json‎

Lines changed: 30 additions & 11 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.
Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
const { findTwoNumsAddingToN, findTwoNumsAddingToN2 } = require('.');
2+
3+
describe('Find two numbers adding to N', () => {
4+
[findTwoNumsAddingToN, findTwoNumsAddingToN2].forEach((func) => {
5+
describe(func.name, () => {
6+
it('Should return an array with length two', () => {
7+
expect(findTwoNumsAddingToN2([1, 2], 3).length).toBe(2);
8+
});
9+
10+
it('Should return false when there is no solution', () => {
11+
expect(findTwoNumsAddingToN2([1, 2], 5)).toBe(false);
12+
});
13+
14+
it('Should return false input array length is less than 2', () => {
15+
expect(findTwoNumsAddingToN2([5], 5)).toBe(false);
16+
});
17+
18+
it('Should return negative values', () => {
19+
expect(findTwoNumsAddingToN2([-2, 1, 2, 6, 7], 5)).toEqual(expect.arrayContaining([-2, 7]));
20+
});
21+
22+
it('Should return two numbers that sum to N', () => {
23+
expect(findTwoNumsAddingToN([1, 2, 3, 5], 5)).toEqual(expect.arrayContaining([2, 3]));
24+
});
25+
});
26+
});
27+
28+
describe('function differences findTwoNumsAddingToN and findTwoNumsAddingToN2', () => {
29+
it('Should return different arrays', () => {
30+
expect(findTwoNumsAddingToN([1, 2, 3, 4], 5))
31+
.toEqual(expect.not.arrayContaining(findTwoNumsAddingToN2([1, 2, 3, 4], 5)));
32+
});
33+
});
34+
});

‎src/_Problems_/find-2-nums-adding-to-n/index.js‎

Lines changed: 8 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -18,15 +18,19 @@ function findTwoNumsAddingToN(arr, number) {
1818

1919
// the Brute force approach
2020
function findTwoNumsAddingToN2(arr, number) {
21-
constpair=[];
21+
2222
for (let i = 0; i < arr.length; i += 1) {
2323
for (let j = i + 1; j < arr.length; j += 1) {
2424
if (arr[i] + arr[j] === number) {
25-
pair.push(arr[i], arr[j]);
26-
break;
25+
return [arr[i], arr[j]];
2726
}
2827
}
2928
}
3029

31-
return pair.length ? pair : false;
30+
return false;
3231
}
32+
33+
module.exports = {
34+
findTwoNumsAddingToN,
35+
findTwoNumsAddingToN2,
36+
};

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /