diff --git a/solutions/19.js b/solutions/19.js new file mode 100644 index 0000000..b785b04 --- /dev/null +++ b/solutions/19.js @@ -0,0 +1,43 @@ +// Find pairs that sum to x +// Return array of pairs from an input array of numbers that adds up to second input x. Each number can be used only once. +// input: [1,2,3,4,5], 6 +// output: [[1,5], [2,4]] + +// Solution by Zach Nagatani @zachnagatani + +/** + * Returns an multidimensional array containing pairs of numbers from an passed in array which add up to the passed in sum + * Each integer can only be used to form one pair + * @param {number[]} arr - An array of numbers to search through + * @param {number} sum - The sum to use as the basis of the search + * @returns {number[][]} pairs - A multidimensional array of pairs that add up to the sum + */ +const solution = (arr, sum) => { + let unusedNums = arr.slice(), + pairs = [], + head = 0, + tail = unusedNums.length - 1; + + while (head < tail) { + let currentSum = unusedNums[head] + unusedNums[tail]; + + if (currentSum === sum) { + pairs.push([unusedNums[head], unusedNums[tail]]); + unusedNums.splice(head, 1); + unusedNums.splice(tail, 1); + + head = 0; + tail = unusedNums.length - 1; + } else if (currentSum < sum) { + head++; + } else { + tail--; + } + } + + return pairs.length ? pairs : null; +}; + +module.exports = { + solution +}; diff --git a/test/19.js b/test/19.js new file mode 100644 index 0000000..a00a46b --- /dev/null +++ b/test/19.js @@ -0,0 +1,23 @@ +const expect = require('chai').expect; +let solution = require('../solutions/19').solution; +//solution = require('../yourSolution').solution; + +describe('Array pairs that sum to x', () => { + it('should return an array of pairs of integers whose sum equal to x', () => { + const result = solution([1,2,3,4,5,6], 6); + expect(result).to.deep.equal([[1,5], [2,4]]); + + const result2 = solution([2,1,3,4,5,6], 6); + expect(result).to.deep.equal([[1,5], [2,4]]); + }); + + it('should only use an integer once in its output', () => { + const result = solution([1,3,3,3], 4); + expect(result).to.deep.equal([[1,3]]); + }); + + it('should return null of no pairs are found', () => { + const result = solution([1,2,3,4,5,6], 40); + expect(result).to.equal(null); + }); +});