检查两个PHP列表是否完全不相交
In PHP, one can use the following function to determine if one list (the child) is a subset of another (the parent):
function issubset($child, $parent)
{
$c = count($child);
$valid = 1;
for($i=0;$i<$c;$i++) {
if(!in_array($child[$i], $parent)) {
$valid = 0;
return $valid;
}
}
return $valid;
}
A similar but opposite concept is the idea of two lists being disjoint, whereby they have no elements in common whatsoever.
For example, the lists 1,2,3,4 and 4,5,6,7 are not disjoint because they have the common element 4, but the lists 1,2,3 and 4,5,6 are disjoint as they have no elements in common.
How might a function to check disjointness be designed?
在PHP中,可以使用以下函数来确定一个列表(子项)是否是另一个列表(子项)的子集( 父级): p>
function issubset($ child,$ parent)
{
$ c = count($ child);
$ valid = 1;
for($ i = 0; $ i&lt; $ c; $ i ++){
if(!in_array($ child [$ i],$ parent)){
$ valid = 0;
return $ valid; \ n}
}
返回$ valid;
}
code> pre>
一个类似但相反的概念是两个列表不相交的想法 em >,它们没有任何共同的元素。 p>
例如,列表1,2,3,4和4,5,6,7并不是不相交的,因为它们有共同点 元素 4 em>,但是列表1,2,3和4,5,6是不相交的,因为它们没有共同的元素。 p>
一个函数怎么可能 检查不相交的设计? p>
div>
if (count(array_intersect($a, $b)) == 0) { /* do something */ }
function disjoint($arr1, $arr2) {
return (count(array_intersect($arr1, $arr2)) == 0);
}
function is_subset($parent, $possible_child) {
return count(array_intersect($parent, $possible_child)) == count($possible_child);
}