对于任何三个给定的集合 A、B 和 C:有没有办法(以编程方式)确定 A 中是否有一个元素是 B 和 C 的合取(编辑:交集)的一部分?
示例:
A:所有大于3的数字
B:所有小于7的数字
C:所有等于 5 的数字
在本例中,集合 A 中有一个适合的元素,即数字 5。我将其作为规范来实现,因此这个数字范围只是一个示例。 A、B、C 可以是任何东西。
最佳答案
编辑: 谢谢尼基!
如果 B.Count <= C.Count <= A.Count
将会有帮助.
D = GetCommonElements(B,C);
if( D.Count>0 && GetCommonElements(D,A).Count >0)
{
// what you want IS NOT EMPTY
}
else
{
// what you want IS EMPTY
}
SET GetCommonElements(X,Y)
{
common = {}
for x in X:
if Y.Contains(x):
common.Add(x);
return common;
}
看看Efficient Set Intersection Algorithm .
我们可以使用distributive laws of sets
if(HasCommonElements(A,B) || HasCommonElements(A,C))
{
// what you want IS NOT EMPTY
}
else
{
// what you want IS EMPTY
}
bool HasCommonElements(X,Y)
{
// if at least one common element is found return true(immediately)
return false
}
关于algorithm - 确定一个集合与另外两个集合的交集是否为空,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2632142/