User Tools

Site Tools


perl:sets

Consider finding the union and intersection of two unique arrays @a and @b:

foreach $e (@a) { $union{$e} = 1 }
foreach $e (@b) {
	if ( $union{$e} ) { $isect{$e} = 1 }
	$union{$e} = 1;
}
@union = keys %union;
@isect = keys %isect;

This would be more idiomatically written as:

foreach $e (@a, @b) { $union{$e}++ && $isect{$e}++ }
@union = keys %union;
@isect = keys %isect;
perl/sets.txt · Last modified: 2009/08/13 09:57 by tkbletsc

Donate Powered by PHP Valid HTML5 Valid CSS Driven by DokuWiki