[Solved] Create coalition combinations with Javascript array


You could use a search and test if the count is smaller then the max items and for the sum of seats.

function getCombinations(array, sum, max) {

    function fork(i, t) {
        var s = t.reduce(function (r, a) { return r + a[2]; }, 0);
        if (s >= sum) {
            result.push([s, t.map(function (a) { return [a[1], a[2]]; })]);
            return;
        }
        if (i < array.length && t.length < max) {
            fork(i + 1, t.concat([array[i]]));
            fork(i + 1, t);
        }
    }

    var result = [];
    fork(0, []);
    return result;
}

var electionResultsData = [["VVD", "vvd", 50, 2504948], ["PVDA", "pvda", 40, 2340750], ["PVV", "pvv", 35, 950263], ["CDA", "cda", 33, 801620], ["SP", "sp", 29, 909853], ["D66", "d66", 26, 757091], ["GL", "gl", 26, 219896], ["CU", "cu", 23, 294586], ["SGP", "sgp", 21, 196780], ["PVDD", "pvdd", 21, 182162], ["50PLUS", "50plus", 21, 177631], ["OVERIG", "overig", 20, 51463], ["PIRATEN", "piraten", 20, 30600], ["LP", "lp", 16, 3335], ["PVDM", "pvdm", 15, 3257], ["JEZUSLFT", "jezuslft", 14, 0], ["ONDRNMR", "ondrnmr", 14, 0], ["LOKAAL", "lokaal", 13, 0], ["ARTIKEL1", "artikel1", 11, 0], ["GEENPEIL", "geenpeil", 11, 0], ["VRIJP", "vrijp", 9, 0], ["BURGBEW", "burgbew", 9, 0], ["FVD", "fvd", 8, 0], ["VDP", "vdp", 8, 0], ["NIEUWEW", "nieuwew", 6, 0], ["DENK", "denk", 5, 0], ["STEMNL", "stemnl", 4, 0], ["VNL", "vnl", 2, 0]],
    result = getCombinations(electionResultsData, 76, 6);
	
document.getElementById('out').appendChild(document.createTextNode(JSON.stringify(result, 0, 4)));
<pre id="out"></pre>

1

solved Create coalition combinations with Javascript array