JSFiddle - React, Tailwind, and code Playground
JavaScript
alert(CombineElements([1,2,3,4], 2));
alert(CombineElements([1,2,3,4,5,6], 3));
alert(CombineElements([1,2,3,4,5,6,7,8,9,0], 5));
function CombineElements(collection, elementCount) {
var combinations = GenerateCombinations(collection.length, elementCount);
var res = [];
for(i = 0; i < combinations.length; i++) {
bitmapIndex = combinations[i].toString(2).split("").reverse().join("");
var arItem = '';
for(j = 0; j < bitmapIndex.length + 1; j++)
{
if (bitmapIndex.substring(j,j+1) == '1')
arItem += collection[j];
}
res.push(arItem);
}
return res;
}
function GenerateCombinations(totalElements, elementCount) {
console.debug('Total de elementos: ' + totalElements);
console.debug('Elementos por combinação: ' + elementCount);
var res = [];
for (i = 0; i < Math.pow(2, totalElements); i++) {
var probe = i.toString(2).replace(new RegExp('0', 'g'), '');
if(probe.length == elementCount)
res.push(i);
}
console.debug(res.length + ' combinações encontradas.');
return res;
}