I want to divide array of n elements to given size subarrays with all possible combinations of elements.
For instance:
Array: {1,2,3,4}
- can be n elements, 1 < n < 100. It can have duplicates.
Given size pattern (just example, could be different): [2 -subarrays, 2-elements]
Expected result:
{1,2},{3,4}
{1,3},{2,4}
{1,4},{2,3}
or
{2,1},{3,4}
{1,3},{4,2}
{3,2},{1,4}
etc.. As You can see, the order of elements in subarrays, or the order of subarrays in sets of subarrays does not matter. It has to be minimum number of sets of the input array subarrays.
I've got to below solution, but it includes also permutations. I need to optimize this to not generate any permutations at all. JavaScript is not necesarry, any language will do. Thanks in advance for any help.
function getN(n, array, subsets) {
var f,
l = array.length,
indices = [],
temp;
array = array.slice();
while (l--) {
f = factorial(l);
indices.push(Math.floor(n / f));
n %= f;
}
temp = indices.map(i => array.splice(i, 1)[0]);
return subsets
? subsets.map((i => l => temp.slice(i, i += l))(0))
: temp;
}
function factorial(num) {
var result = 1;
while (num) {
result *= num;
num--;
}
return result;
}
var i, l,
array = ['1', '2', '3', '4'],
subsets = [2, 2],
pre = document.getElementById('out');
for (i = 0, l = factorial(array.length); i < l; i++) {
pre.innerHTML += i.toString().padStart(4) +': ' + JSON.stringify(getN(i, array, subsets)) + '\n';
}
<pre id="out"></pre>