Perl Christmas Quiz

Jasper jaspermccrea at gmail.com
Fri Dec 12 17:40:02 GMT 2008


2008/12/12 Uri Guttman <uri at stemsystems.com>:
>>>>>> "UG" == Uri Guttman <uri at stemsystems.com> writes:
>
>>>>>> "CJ" == Chris Jack <chris_jack at msn.com> writes:
>  CJ> 3) Write a Perl function that takes two references to arrays and
>  CJ> returns the intersect of them. If an entry appears n times in
>  CJ> array 1 and m times in array 2, the output should list that entry
>  CJ> min(n,m) times. Bonus mark for one line solutions.
>
>  UG> this appears to work fine and is a true one line sub.
>
>  UG> use strict ;
>  UG> use warnings ;
>
>  UG> sub intersect {
>
>  UG>   return keys %{{ map {$_, 1} grep(exists ${{map { $_ => 1 } @{$_[0]}}}{$_}, @{$_[1]}) }} ;
>  UG> }
>
> and i squeezed out the white space and dropped the superfluous exists to
> get this version:
>
>        return keys%{{map{$_,1}grep(${{map{$_=>1}@{$_[0]}}}{$_},@{$_[1]})}} ;
>

Uri, I don't believe this does the right thing with regard to multiple
occurrences of an entry in both arrays. I may be wrong.

I think this works

sub intersect {grep(!++$_[2]->{$_},@{$_[0]}),grep 1x$_[2]->{$_}--,@{$_[1]}}

Bit of a cheat using $_[2], though

-- 
Jasper


More information about the london.pm mailing list