你没有说集合是如何表示的,所以我使用数组来达到这个目的。
// The base set
$baseSet = array('A', 'B', 'C', 'D');
// Build the subsets
$subSets = array();
for ($i = 0; $i < 3; $i++) {
for ($j = $i+1; $j< 4; $j++) {
$subSets[] = array($baseSet[$i], $baseSet[$j]);
}
}
有了这个,解决方案很简单:
foreach ($subSets as $subSet) {
$complement = array_diff($baseSet, $subSet);
printf("{%s, %s} - {$s, %s}\n",
$baseSet[0], $baseSet[1],
$complement[0], $complement[1]
);
}
一般来说,PHP 提供了很多与数组相关的集合函数。
如果您只想比较两个子集,请使用array_intersect()
:
$common = array_intersect($subSet1, $subSet2);
if (empty($common)) {
echo 'The subsets are distinct.';
} else {
echo 'The subsets have these elements in common: ' . implode(', ', $common);
}