Below is widely known combination function.
function getCombination(arr,selectNumber){
const result = [];
if(selectNumber == 1) {
return arr.map(el => [el])
};
arr.forEach((fixed, index, array)=>{
const rest = array.slice(index+1);
const combinations = getCombination(rest, selectNumber - 1);
const attached = combinations.map((el => [fixed,...el]));
result.push(...attached);
});
return result;
};
I traced code and found some useless calculations when (index == array.length-1) in forEach segment. so I added "if()" in that. is it always return correct results?
function getCombination(arr,selectNumber){
const result = [];
if(selectNumber == 1) {
return arr.map(el => [el])
};
arr.forEach((fixed, index, array)=>{
if(index == array.length-1) return; /* I added this line */
const rest = array.slice(index+1);
const combinations = getCombination(rest, selectNumber - 1);
const attached = combinations.map((el => [fixed,...el]));
result.push(...attached);
});
return result;
};