0

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

2
  • 2
    Please show what you've tried, we're not here to write it for you, we're here to help you fix your bugs. Commented Feb 22, 2014 at 9:37
  • I am not expecting a fully working code, I can write it my self, what I need is just a hint in the right direction. @Jack No, rows and columns are dynamic. Commented Feb 22, 2014 at 9:41

3 Answers 3

4

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);
Sign up to request clarification or add additional context in comments.

Comments

1

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];
}

Comments

1
  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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.