如何解决java通过排除元素将一个列表分成多个列表
有一个List,其中的元素根据某些条件是互斥的
-
现在我需要根据这种互斥条件将列表分为多个
-
在分区后,互斥元素不能出现在子列表中
-
分段后的子列表数量应最小化
-------------例如----------------------
-
原始列表[A,B,C]
-
A和C互斥,A和B不互斥,B和C不互斥
-
它可以分为[A],[B,C]或[C],[A,B]
-
请勿拆分为[A],[B],[C],因为拆分后的子列表总数不是最小值
谁可以帮助我?
解决方法
据我了解,您希望基于集合中任意两个元素之间的任意比较来对集合元素进行分区。我不认为Java带有此功能。您可以执行以下操作的一种方法:
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="oval">
<stroke android:width="2dp"
android:color="#747474"/>
</shape>
您可以像这样测试您的方案:
public class Partition<T> {
public List<Set<T>> partition(List<T> list,BiPredicate<T,T> partitionCondtion) {
List<Set<T>> partition = new ArrayList<>();
while (!list.isEmpty()) {
// get first element from the remaining elements on the original list
T firstElement = list.remove(0);
// add first element into a subset
// all elements on this subset must not be mutually exclusive with firstElement
Set<T> subset = new HashSet<>();
subset.add(firstElement);
// get all remaining elements which can reside in the same subset of
// firstElement
List<T> notMutuallyExclusive = list.stream().filter(e -> !partitionCondtion.test(firstElement,e))
.collect(Collectors.toList());
// add them to the subset of firstElement
subset.addAll(notMutuallyExclusive);
// add subset to partition (list of subsets)
partition.add(subset);
// remove elements added from original list
list.removeAll(notMutuallyExclusive);
}
return partition;
}
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。