Perl Christmas Quiz
Hakim Cassimally
hakim.cassimally at gmail.com
Fri Dec 12 14:15:49 GMT 2008
On 12/12/2008, Peter Corlett <abuse at cabal.org.uk> wrote:
> On Fri, Dec 12, 2008 at 01:18:24PM +0000, Hakim Cassimally wrote:
> [...]
>
> > The question isn't specific about how the output should look if it a key
> > doesn't appear in both arrays, or if n==m.
>
>
> It does. It asks for the "intersect", which is the set theory way of saying
> "those elements that appear in both sets, and no others".
>
> Here's my attempt:
>
> sub intersect{my%x;$x{$_}++for(@{+shift});grep{$x{$_}&&$x{$_}--}@{+shift};}
Gah of course: though you missed the min(n,m) requirement. So
sub uniqc { my %seen; $seen{$_}++ for @_; \%seen }
sub intersect {
my @lists = map uniqc(@$_), @_;
+{ map {
my $key = $_;
my @vals = grep $_, map { $_->{$key} } @lists;
@vals == @lists ?
do {
my ($min, $max) = (sort {$a<=>$b} @vals)[0,-1];
($key => $min==$max ? $min : "min($min,$max)");
}
: ();
} keys %{ uniqc map @$_, @_ }
}
}
More information about the london.pm
mailing list