javascript - Creating permutations to reach a target number -
i have array [1, 2, 4] , want make 4; want return [4], not [[1,1,1,1], [1,1,2], [2,2], [4]], doing started run out of memory when running on small server. had let whole function run through .reverse() because last time in array useful me.
if think of in terms of currency, let's take [0.5, 0.5, 1, 0.2]; if want $1, want [1] , not [0.5, 0.5] because want largest value per item right?
i'm using this:
function getcombinations(array, sum) { function fork(i, t) { var s = t.reduce(function (a, b) { return + b; }, 0); if (sum === s) { result.push(t); return; } if (s > sum || === array.length) { return; } fork(i + 1, t.concat([array[i]])); fork(i + 1, t); } var result = []; fork(0, []); return result; } console.log(getcombinations([1, 2, 4], 4)); .as-console-wrapper { max-height: 100% !important; top: 0; } but doesn't work backwards, made iterate backwards:
function getcombinations(array, sum) { function fork(i, t) { var s = t.reduce(function (a, b) { return + b; }, 0); if (sum === s) { result.push(t); return; } if (s > sum || === 0) { return; } fork(i - 1, t.concat([array[i]])); fork(i - 1, t); } var result = []; fork(array.length, []); return result; } console.log(getcombinations([1, 2, 4], 4)); .as-console-wrapper { max-height: 100% !important; top: 0; } but doesn't work large-scale operations i'm using, example i'm trying do:
warning: may crash browser
function getcombinations(array, sum) { function fork(i, t) { var s = t.reduce(function (a, b) { return + b; }, 0); if (sum === s) { result.push(t); return; } if (s > sum || === 0) { return; } fork(i - 1, t.concat([array[i]])); fork(i - 1, t); } var result = []; fork(array.length, []); return result; } var items = []; for(var j = 0; j < 7; j++) items.push(0.11); for(var k = 0; k < 197; k++) items.push(1); console.log(getcombinations(items, 26.77)); .as-console-wrapper { max-height: 100% !important; top: 0; }
Comments
Post a Comment