Given an array
a
, check to see ifz
numbers insidea
total up ton
.If
a = [1,2,3]
,n=3
andz=2
, then this function should returntrue
, sincez
numbers in that array combine to equaln
.
I recently took a test for a job to fill out this function, and this was my answer. It was presumably rejected by the robots for being too slow, since one of the tests terminated with a timeout error.
var isSumPossible = function isSumPossible(a, n, z) {
return +a.some(function (val, ix) {
return z === 1 ? val === n : isSumPossible(a.slice(ix - 1, ix).concat(a.slice(ix + 1)), n - val, z - 1);
});
};
How can this code be optimized to make it faster?