Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get a list of combinations of lists' elements

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.

like image 762
Alexiy Avatar asked Jan 30 '14 12:01

Alexiy


1 Answers

For the lazy (using Guava):

Set<List<String>> result = Sets.cartesianProduct(
                ImmutableSet.of("q", "w"),
                ImmutableSet.of("a", "s"),
                ImmutableSet.of("z", "x")
        );

System.out.println(result);

output:

[ [q, a, z], [q, a, x], [q, s, z], [q, s, x], [w, a, z], [w, a, x], [w, s, z], [w, s, x] ]

like image 197
Neil McGuigan Avatar answered Sep 25 '22 18:09

Neil McGuigan