获取列表元素的组合列表
假设我有3个列表:[‘q’,’w’],[‘a’,’s’],[‘z’,’x’]。 如何从这些列表中获取可能的组合列表? 所以我得到一个列表[[‘q’,’a’,’z’],[‘q’,’s’,’z’]]等等。 我为两个方法制作了一个方法,但是无法为N个列表找到一个方法:
static ArrayList combine(ArrayList one,ArrayList two) { ArrayList<ArrayList> combs=new ArrayList<ArrayList>(); 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完成的。
你需要N个嵌套循环,这就是它的难点。
你可以使用递归来实现这一点。
static ArrayList combine(ArrayList soFar, ArrayList ... 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> combs=new ArrayList>(); // Loop through the first list looking for elements for(E e:lists[0]) { // Create a new List to build this combination ArrayList 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 ArrayList combine(ArrayList ... lists) return combine(new ArrayList (), lists); }
对于懒惰(使用番石榴):
Set> result = Sets.cartesianProduct( ImmutableSet.of("q", "w"), ImmutableSet.of("a", "s"), ImmutableSet.of("z", "x") ); System.out.println(result);
输出:
[ [q, a, z], [q, a, x], [q, s, z], [q, s, x], [w, a, z], [w, a, x], [w, s, z], [w, s, x] ]
你可能想看一下https://github.com/javagl/Combinatorics/blob/master/src/main/java/de/javagl/utils/math/combinatorics/MixedRangeCombinationIterable.java这个class(一个“独立的”)类,只需复制并插入到您的项目中)
用法示例:
import java.util.ArrayList; import java.util.Arrays; import java.util.List; public class Combinations { public static void main(String[] args) { List> lists = new ArrayList>(); lists.add(Arrays.asList('q','w')); lists.add(Arrays.asList('a','s')); lists.add(Arrays.asList('z','x')); MixedRangeCombinationIterable iterable = new MixedRangeCombinationIterable (lists); for (List element : iterable) { System.out.println(element); } } }
您实际上正在计算输入集的http://en.wikipedia.org/wiki/Cartesian_product的元素
您可以使用构造函数(参数…)创建内部类,因此您可以放置此类的列表来处理所有组合