Last active
August 29, 2015 14:25
-
-
Save justsml/0ee76572579fa4bee33f to your computer and use it in GitHub Desktop.
sum-sub-sequence-challenge! This simplified version has notable enhancements missing like, using a hashtable, memoization, and an optimal sort or partial-sort step.
This file contains 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
module.exports = function(numArray) { | |
var args = [].slice.call(arguments); | |
if ( args.length < 2 ) { throw new Error('Invalid parameters'); } | |
if ( !Array.isArray(numArray) ) { throw new Error('Invalid Input, Must be Array'); } | |
var findSums = args.slice(1, args.length); | |
// unpack sums if array, or use arguments[1:] | |
findSums = Array.isArray(findSums[0]) ? findSums[0] : findSums; | |
return numArray.some(checkSums, findSums); | |
} | |
function checkSums(val, index, arr) { | |
return arr.some(function(innerVal, innerIndex) { | |
return this.indexOf(val + innerVal) > -1; | |
}, this); | |
} |
This file contains 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
{ | |
"name": "sum-sub-sequence-challenge", | |
"version": "0.0.0", | |
"description": "", | |
"main": "test.js", | |
"scripts": { | |
"test": "node test.js" | |
}, | |
"author": "", | |
"license": "MIT", | |
"dependencies": { | |
"tape": "^4.0.1" | |
} | |
} |
This file contains 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
var test = require('tape'); | |
var sumArray = require('./index'); | |
var x = [1, 2, 6, 9, -1, 38947, 55, 81]; | |
test('find sub-array pair, matching given sum', function (t) { | |
t.plan(4); | |
t.ok(sumArray(x, 10)); | |
t.ok(sumArray(x, 8)); | |
t.ok(!sumArray(x, 99)); | |
t.ok(sumArray(x, 38948)); | |
}); | |
test('find sub-array pair, matching any sum(s) provided', function (t) { | |
t.plan(5); | |
t.ok(sumArray(x, 999, 8)); | |
t.ok(!sumArray(x, 99, 12999)); | |
t.ok(!sumArray(x, [99, 12999])); | |
t.ok(sumArray(x, 38948)); | |
t.ok(sumArray(x, [38948])); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment