Creating permutations to reach a target number

帅比萌擦擦* 提交于 2019-12-23 03:27:03

问题


I have the array [1, 2, 4] and I want to make 4; I want it to return [4], not [[1,1,1,1], [1,1,2], [2,2], [4]], I was previously doing this but I started to run out of memory when running this on a small server. I had to let the whole function run through so I could .reverse() because the last time in the array was only useful to me.

If we think of this in terms of currency, let's take [0.5, 0.5, 1, 0.2]; if I want $1, I want [1] and not [0.5, 0.5] because you always want the largest value per item right?

I'm currently using this:

function getCombinations(array, sum) {

    function fork(i, t) {
        var s = t.reduce(function (a, b) { return a + b; }, 0);
        if (sum === s) {
            result.push(t);
            return;
        }
        if (s > sum || i === 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 this doesn't work backwards, so I made it iterate backwards:

function getCombinations(array, sum) {

    function fork(i, t) {
        var s = t.reduce(function (a, b) { return a + b; }, 0);
        if (sum === s) {
            result.push(t);
            return;
        }
        if (s > sum || i === 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 this doesn't work for large-scale operations like I'm using, for example I'm trying to do:

WARNING: THIS MAY CRASH YOUR BROWSER

function getCombinations(array, sum) {

    function fork(i, t) {
        var s = t.reduce(function (a, b) { return a + b; }, 0);
        if (sum === s) {
            result.push(t);
            return;
        }
        if (s > sum || i === 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; }

来源:https://stackoverflow.com/questions/43254801/creating-permutations-to-reach-a-target-number

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!