Salman
Salman

Reputation: 9447

Combinations of elements of multiple arrays

I have this type of data

var arr = [
    ["A", "AA"],
    ["B"],
    ["C", "CC", "CCC"]
];

I want to get combinations of all the elements within each array. for e.g.

A B
A B C
A B CC
A B CCC
A C
A CC
A CCC
...
AA B CCC

Note the sequence of the words are same, like this should not be one of the combination B A C.

I tried a couple of logics but can't get what I am looking for. I can obtain all permutations and combinations of all the words, but that's not what I am looking for.

Please suggest

Upvotes: 0

Views: 1038

Answers (3)

Ja͢ck
Ja͢ck

Reputation: 173542

You basically want to permute across multiple lists:

function permute(input)
{
  var out = [];

  (function permute_r(input, current) {
    if (input.length === 0) {
      out.push(current);
      return;
    }

    var next = input.slice(1);

    for (var i = 0, n = input[0].length; i != n; ++i) {
      permute_r(next, current.concat([input[0][i]]));
    }
  }(input, []));

  return out;
}

permute(arr);

Upvotes: 4

chill
chill

Reputation: 16888

  1. Make an array of indices (idx), each element corresponding to each row. Initial value 0.
  2. Start with index i = 0
  3. Do what you do with the current combination.
  4. Increment idx[i]. If it's less than the length of the row, go to 2
  5. Set idx[i] to zero
  6. Increment i. If it's greater than the number of rows, terminate algorithm, otherwise go to 2

Upvotes: 1

Buch
Buch

Reputation: 92

The problem can be solved recursively. That is: for the first array, you have, for each of the elements, the result of the combinations formed with the two other arrays.

Something like this could work:

function arrayCombine ( array ) {
    if (array.length > 1) {
        var result = new Array();

        //This combines all the arrays except the first
        var otherCombs = arrayCombine ( array.slice(1) );

        for ( var n = 0; n < array[0].length; n++ )
            for ( var i = 0; i < otherCombs.length; i++ )
                result.push ( array[0][n] + otherCombs[i] );

        return result;                
    }

    //If we have only one array, the result is the array itself, for it contains in itself all the combinations of one element that can be made
    else return array[0];
}

Upvotes: 1

Related Questions