Skip to content

Commit f477a64

Browse files
author
John Allsup
committed
Added family intersection and union
1 parent 48c0104 commit f477a64

File tree

1 file changed

+55
-0
lines changed

1 file changed

+55
-0
lines changed

src/Set.php

Lines changed: 55 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -282,4 +282,59 @@ public function offsetUnset($offset) : void
282282

283283
$this->size = $this->count();
284284
}
285+
286+
/**
287+
* Create a function given an array
288+
*
289+
* @param array $elements The array of elements to create the set from
290+
* @return Set
291+
*/
292+
public static function FromArray($elements) : Set
293+
{
294+
$set_reflector = new \ReflectionClass("\PhpSets\Set");
295+
296+
return $set_reflector->newInstanceArgs($elements);
297+
}
298+
299+
/**
300+
* Union of a family (array) of sets
301+
* ([a,b,c]) => a u b u c
302+
*
303+
* @param array $sets -- the family of sets to take the union of
304+
* @return Set
305+
*/
306+
public static function UnionOfArray(array $sets) : Set
307+
{
308+
/* trivial cases */
309+
if( count($sets) == 0 ) return new Set();
310+
if( count($sets) == 1 ) return $sets[0];
311+
312+
$result = array_shift($sets);
313+
foreach($sets as $set) {
314+
$result = $result->union($set);
315+
}
316+
317+
return $result;
318+
}
319+
320+
/**
321+
* Intersection of a family (array) of sets
322+
* ([a,b,c]) => a n b n c
323+
*
324+
* @param array $sets -- the family of sets to take the intersection of
325+
* @return Set
326+
*/
327+
public static function IntersectionOfArray(array $sets) : Set
328+
{
329+
/* trivial cases */
330+
if( count($sets) == 0 ) return new Set(); # should be error, not {}
331+
if( count($sets) == 1 ) return $sets[0];
332+
333+
$result = array_shift($sets);
334+
foreach($sets as $set) {
335+
$result = $result->intersect($set);
336+
}
337+
338+
return $result;
339+
}
285340
}

0 commit comments

Comments
 (0)