0

How can I loop through an array of string values and output all combinations for N number of string values?

I also need to preserve each combination so that I can loop through those for creating records in a database.

I found a combination generator that helps require a minimum and I modified it as follows:

var combine = function(a, min) {
var fn = function(n, src, got, all) {
    if (n == 0) {
        if (got.length > 0) {
            all[all.length] = got;
        }
        return;
    }
    for (var j = 0; j < src.length; j++) {
        fn(n - 1, src.slice(j + 1), got.concat([src[j]]), all);
    }
    return;
}
var all = [];
for (var i = min; i < a.length; i++) {
    fn(i, a, [], all);
}
all.push(a);
return all;
}

var subsets = combine(["RT","PT","DDA"], 1);

This outputs:

RT,PT,DDA,RT,PT,RT,DDA,PT,DDA,RT,PT,DDA

Which technically has all of the correct outputs, but I need to break them up into unique combos so that it outputs like this:

[[RT],[PT],[DDA],[RT,PT],[RT,DDA],[PT,DDA],[RT,PT,DDA]]

Having an array of arrays would allow me to loop through using the index later on to create unique records in the database. That's my thought at least and I could really use some help as I am still trying to fully understand recursive functions.

Ratner
  • 11
  • 3

1 Answers1

0

Note that every combination (including empty one) of N items corresponds to binary number K in range 0..2^N-1. If K contains 1 bit in i-th position, then i-th item is included in K-th combination. For example, value k=5=101binary corresponds to the combination of 0-th and 2-th item ([RT,DDA] in your case).

So just make loop for K=1..2^N-1, examine bits of K and build corresponding combination. Pseudocode:

for (k = 1; k < (1 << N); k++):
    comb = []
    t = k
    idx = 0
    while t > 0:
        if (t and 1):
           comb = comb + A[idx]               
        t = t << 1
        idx++
MBo
  • 77,366
  • 5
  • 53
  • 86