Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Unit tests & fix for "find-2-nums-adding-to-n" #19

Merged
merged 1 commit into from
Oct 3, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
41 changes: 30 additions & 11 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
const { findTwoNumsAddingToN, findTwoNumsAddingToN2 } = require('.');

describe('Find two numbers adding to N', () => {
[findTwoNumsAddingToN, findTwoNumsAddingToN2].forEach((func) => {
describe(func.name, () => {
it('Should return an array with length two', () => {
expect(findTwoNumsAddingToN2([1, 2], 3).length).toBe(2);
});

it('Should return false when there is no solution', () => {
expect(findTwoNumsAddingToN2([1, 2], 5)).toBe(false);
});

it('Should return false input array length is less than 2', () => {
expect(findTwoNumsAddingToN2([5], 5)).toBe(false);
});

it('Should return negative values', () => {
expect(findTwoNumsAddingToN2([-2, 1, 2, 6, 7], 5)).toEqual(expect.arrayContaining([-2, 7]));
});

it('Should return two numbers that sum to N', () => {
expect(findTwoNumsAddingToN([1, 2, 3, 5], 5)).toEqual(expect.arrayContaining([2, 3]));
});
});
});

describe('function differences findTwoNumsAddingToN and findTwoNumsAddingToN2', () => {
it('Should return different arrays', () => {
expect(findTwoNumsAddingToN([1, 2, 3, 4], 5))
.toEqual(expect.not.arrayContaining(findTwoNumsAddingToN2([1, 2, 3, 4], 5)));
});
});
});
12 changes: 8 additions & 4 deletions src/_Problems_/find-2-nums-adding-to-n/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -18,15 +18,19 @@ function findTwoNumsAddingToN(arr, number) {

// the Brute force approach
function findTwoNumsAddingToN2(arr, number) {
const pair = [];

for (let i = 0; i < arr.length; i += 1) {
for (let j = i + 1; j < arr.length; j += 1) {
if (arr[i] + arr[j] === number) {
pair.push(arr[i], arr[j]);
break;
return [arr[i], arr[j]];
}
}
}

return pair.length ? pair : false;
return false;
}

module.exports = {
findTwoNumsAddingToN,
findTwoNumsAddingToN2,
};