gpt4 book ai didi

java - 找到所有集合的组合 - 设置封面?

转载 作者:塔克拉玛干 更新时间:2023-11-03 03:32:11 24 4
gpt4 key购买 nike

有人可以分享一个 java 程序,它执行以下操作。如果给出以下集合作为输入,

a={1,2,3,8,9,10}
b={1,2,3,4,5}
c={4,5,7}
d={5,6,7}
e={6,7,8,9,10}

U={1,2,3,4,5,6,7,8,9,10}

程序会找出集合的所有组合,并找出最少的集合中包含 U 的所有元素的集合。

在上面的例子中,最小的数量是2。设置b和e一起覆盖整个U。所以基本上,这是一个集合覆盖问题。在集合覆盖问题中,给定一个宇宙 U,满足 |U|=n,集合 S1,……,Sk 是 U 的子集。 cover 是 S1,……,Sk 中的一些集合 C 的集合 C,其联合是整个宇宙 U。此外,我们必须最小化集合的成本。

最佳答案

你需要的是测试不断增加的组合大小,就像这样

interface Filter<T> {
boolean matches(T t);
}
public static void main(String... args) throws IOException {
Integer[][] arrayOfSets = {
{1, 2, 3, 8, 9, 10},
{1, 2, 3, 4, 5},
{4, 5, 7},
{5, 6, 7},
{6, 7, 8, 9, 10},
};
Integer[] solution = {1,2,3,4,5,6,7,8,9,10};

List<Set<Integer>> listOfSets = new ArrayList<Set<Integer>>();
for (Integer[] array : arrayOfSets)
listOfSets.add(new LinkedHashSet<Integer>(Arrays.asList(array)));
final Set<Integer> solutionSet = new LinkedHashSet<Integer>(Arrays.asList(solution));

Filter<Set<Set<Integer>>> filter = new Filter<Set<Set<Integer>>>() {
public boolean matches(Set<Set<Integer>> integers) {
Set<Integer> union = new LinkedHashSet<Integer>();
for (Set<Integer> ints : integers)
union.addAll(ints);
return union.equals(solutionSet);
}
};

Set<Set<Integer>> firstSolution = shortestCombination(filter, listOfSets);
System.out.println("The shortest combination was "+firstSolution);
}

private static <T> Set<T> shortestCombination(Filter<Set<T>> filter, List<T> listOfSets) {
final int size = listOfSets.size();
if (size > 20) throw new IllegalArgumentException("Too many combinations");
int combinations = 1 << size;
List<Set<T>> possibleSolutions = new ArrayList<Set<T>>();
for(int l = 0;l<combinations;l++) {
Set<T> combination = new LinkedHashSet<T>();
for(int j=0;j<size;j++) {
if (((l >> j) & 1) != 0)
combination.add(listOfSets.get(j));
}
possibleSolutions.add(combination);
}
// the possible solutions in order of size.
Collections.sort(possibleSolutions, new Comparator<Set<T>>() {
public int compare(Set<T> o1, Set<T> o2) {
return o1.size()-o2.size();
}
});
for (Set<T> possibleSolution : possibleSolutions) {
if (filter.matches(possibleSolution))
return possibleSolution;
}
return null;
}

打印

The shortest combination was [[1, 2, 3, 4, 5], [6, 7, 8, 9, 10]]

关于java - 找到所有集合的组合 - 设置封面?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4287302/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com