如何迭代所有可能性将一个ArrayList拆分为两个大小为k和(n-k)的ArrayLists?

时间:2014-11-26 20:11:21

标签: java algorithm arraylist

我正在寻找一种迭代所有可能性的方法,将数组列表拆分为两个数组列表,其中第一个包含k个元素,第二个包含其余数据列表。

例如,在Python中我会写

import itertools
my_set = {1,2,3,4,5}
k = 2
map(lambda x: (set(x), my_set-set(x)), itertools.combinations(my_set, k))

会给出:

[(set([1, 2]), set([3, 4, 5])),
 (set([1, 3]), set([2, 4, 5])), 
 (set([1, 4]), set([2, 3, 5])), 
 (set([1, 5]), set([2, 3, 4])), 
 (set([2, 3]), set([1, 4, 5])), 
 (set([2, 4]), set([1, 3, 5])), 
 (set([2, 5]), set([1, 3, 4])), 
 (set([3, 4]), set([1, 2, 5])), 
 (set([3, 5]), set([1, 2, 4])), 
 (set([4, 5]), set([1, 2, 3]))]

如何在Java中获取给定集合(well,ArrayList)的所有k元素子集?

1 个答案:

答案 0 :(得分:1)

在评论中使用@zapl中提到的来自Guava的Collections2,您可以在Java8中执行类似的操作:

final List<Integer> xs = Arrays.asList(1, 2, 3, 4, 5);
final int k = 2;
Collections2.permutations(xs)
    .stream()
    .map(list -> Arrays.asList(new HashSet<>(list.subList(0, k)),
        new HashSet<>(list.subList(k, xs.size()))))
    .distinct()
    .forEach(System.out::println);

哪会导致

[[1, 2], [3, 4, 5]]
[[1, 5], [2, 3, 4]]
[[1, 4], [2, 3, 5]]
[[4, 5], [1, 2, 3]]
[[1, 3], [2, 4, 5]]
[[3, 5], [1, 2, 4]]
[[3, 4], [1, 2, 5]]
[[2, 3], [1, 4, 5]]
[[2, 5], [1, 3, 4]]
[[2, 4], [1, 3, 5]]