Jasper
Fri, 12 Dec 2008 09:48:31 -0800
2008/12/12 Uri Guttman <u...@stemsystems.com>:
>>>>>> "UG" == Uri Guttman <u...@stemsystems.com> writes:
>
>>>>>> "CJ" == Chris Jack <chris_j...@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