...and the hash technique can be made slightly better:
sub isSubsetHash2 { my @small = split ':', $_[0]; my %big; @big{ split( ':', $_[1] ) } = (); return scalar( @small ) == grep { exists $big{$_} } @small; }
This eliminates the counter variable, and takes advantage of the fact that in scalar (boolean) context grep doesn't bother generating a list, only a count.
These are all micro-optimizations though. The most important optimization is to choose the proper algorithm. And in the case of finding set intersections, a hash-based algorithm is nearly always going to be the right one.
The hash technique will keep on getting better and better, too, as compared to the other algorithms. As the size of @small increases, you would be doing more and more linear searches over @big with the smart match approaches. Yet for the hash approach, once the big hash is built, each element in @small can be checked in constant time. Try 1000 elements in @big and 400 in @small.
Dave
In reply to Re^4: Computing Subsets
by davido
in thread Computing Subsets
by grandpascorpion
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |