获取列表元素的组合列表 [英] Get a list of combinations of lists' elements

查看:76
本文介绍了获取列表元素的组合列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有3个列表:['q','w'],['a','s'],['z','x']。如何从这些列表中获取可能的组合列表?所以我得到一个列表[['q','a','z'],['q','s','z']]等等。我为两个方法制作了一个方法,但是不能为N个列表找到一个方法:

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

我发现这是由Guava的Sets.cartesianProduct完成的。​​

I found out that this is done by Guava's Sets.cartesianProduct.

推荐答案

你需要N个嵌套循环,这就是它的难点。

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

这篇关于获取列表元素的组合列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆