Get a list of combinations of lists' elements

combinatorics, java

Solution

You need N nested loops, which is what makes it hard.

You can achieve this using recursion though.

static <E> ArrayList combine(ArrayList<E> soFar, ArrayList<E>... lists)
{
    // Rather than constantly making and remaking this list could just use one
    // and pass it around and add stuff to it. This works though.
    ArrayList<ArrayList<E>> combs=new ArrayList<ArrayList<E>>();

    // Loop through the first list looking for elements
    for(E e:lists[0])
    {
       // Create a new List to build this combination
       ArrayList<E> temp = new ArrayList<>(soFar);
       // Add this element to the combination
       temp.add(e);
       // If there are more lists recurse down
       if (lists.length > 1) {
           // Use recursion to add all combinations of the remaining lists
           combs.addAll(combine(temp, lists.subList(1)));
       } else {
           // There are no more lists so we are done, add temp to the combos
           combs.add(temp);
       }
    }
    return combs;
}


// Call this method to start things going, the other one should probably be private
static <E> ArrayList combine(ArrayList<E>... lists)
    return combine(new ArrayList<E>(), lists);
}

Problem

Suppose I have 3 lists: ['q','w'], ['a','s'], ['z','x']. How to get a list of possible combinations out of these lists? So I get a list [['q','a','z'],['q','s','z']] and such. I made a method for two, but can't figure one for N lists: ``` static <E> ArrayList combine(ArrayList<E> one,ArrayList<E> two) { ArrayList<ArrayList<E>> combs=new ArrayList<ArrayList<E>>(); for(E e:one) { for(E e2:two) { ArrayList ps=new ArrayList(); ps.add(e); ps.add(e2); combs.add(ps); } } return combs; } ``` I found out that this is done by Guava's Sets.cartesianProduct.

Original source