1

I've been trying to design an algorithm that would generate all possible variants of a given sequence through concatenation of arrays containing different variants of a single piece of that sequence. I have a JS object that looks somewhat like this:

[[a1, a2], [b1, b2, b3], [c1]]

What I need as an output would look like this:

[[a1, b1, c1], [a1, b2, c1], [a1, b3, c1], [a2, b1, c1], [a2, b2, c1], [a2, b3, c1]]

The number of variants contained within subarrays can vary depending on the input, so can the length of the encompassing array itself. The order of elements must be conserved (so simple permutation does not solve the problem).

I've come up with the following code:

var temp = []
var final = []
for (var i = 0; i < array.length; i=i+2) {
  var current = array[i] //store first batch of variants in a variable
  if(array[i+1] != undefined){ var next = array[i+1] //store next batch of variants
  for (var a = 0; a < current.length; a++) {
    for (var b = 0; b < next.length; b++) {
      temp.push(current[a].concat(next[b])); 
      //push current variant of the first object and 
      //current variant of the second object into an array
          final.push(temp); //record the array
          temp = []; //renew the temporary array
        }
      }
    }
    }
    return final;

This seems to work if I feed it with a sequence that contains just two elements, however any longer sequence doesn't work. How can I overwork the above code to work for longer sequences? Has anyone have a better idea on how to handle it? Also, please excuse me if I'm missing something obvious, I'm still in the phase of getting the hang of coding.

  • "*How can I overwork the above code to work for longer sequences?*" - Recursion to the rescue. You can try it yourself, or look at the duplicate answers for a complete solution :-) – Bergi Aug 27 '17 at 13:47
  • https://stackoverflow.com/questions/12303989/cartesian-product-of-multiple-arrays-in-javascript – MBo Aug 27 '17 at 13:47
  • @Bergi Thank you very much, the cartesian product solves everything. Took me a while to grasp how it works but now it's clear, how that sweet recursion works. Next time I'll be more thorough while searching for a solution in order not to duplicate questions. :) – Krzysztof Czarnecki Aug 27 '17 at 20:38

0 Answers0