Desired output of a routine:
combine(0,[1,2,3]) => [[]] // as N choose 0 = 1
combine(1,[1,2,3]) => [[1],[2],[3]] // as N choose 1 = N
combine(2,[1,2,3]) => [[1,2],[1,3],[2,3]]]] // as N choose N-1 = N
combine(3,[1,2,3]) => [[1,2,3]] // as N choose N = 1
combine(0,[1,2,3,4]) => [[]] // as N choose 0 = 1
combine(1,[1,2,3,4]) => [[1],[2],[3],[4]] // as N choose 1 = N
combine(2,[1,2,3,4]) => [[1,2],[1,3],[1,4],[2,3],[2,4],[3,4]]]] // as 4 choose 2 = 6
combine(3,[1,2,3,4]) => [[1,2,3],[1,2,4],[1,3,4],[2,3,4]] // as N choose N-1 = N
combine(4,[1,2,3,4]) => [[1,2,3,4]] // as N choose N = 1
const combine = (x, list) => {
if(list.length < x){
throw new Error('not enough elements to combine.');
}
if(list.length < 1){
return [];
}
if (x === 0) {
return list.slice(0)
}
const ret = [];
for(let v of combine(x-1, list.slice(1))){
ret.push([list[0], ...v]);
}
return ret;
}
Have a look at the answer on stackoverflow its a perfect match to what you are trying to do. https://stackoverflow.com/questions/64414816/can-you-return-n-choose-k-combinations-in-javascript-using-array-flatmap/64414875#64414875.
Even with the conditions above you are getting "Uncaught TypeError: v is not iterable"