Perl Christmas Quiz

Peter Corlett abuse at cabal.org.uk
Fri Dec 12 14:33:59 GMT 2008


On Fri, Dec 12, 2008 at 02:15:49PM +0000, Hakim Cassimally wrote:
> On 12/12/2008, Peter Corlett <abuse at cabal.org.uk> wrote:
[...]
>> sub intersect{my%x;$x{$_}++for(@{+shift});grep{$x{$_}&&$x{$_}--}@{+shift};}
> Gah of course: though you missed the min(n,m) requirement.

Are you sure? Really sure?

The basic algorithm is to take the first list and build up a frequency
table. It then iterates over the second list and returns a value if and only
if it appears in the frequency table, decrementing the count in the table.

So if n > m, the decrement will never reach zero, and all m entries in the
second list will be returned; for n <= m, the decrement will reach zero and
only the first n entries in the second list will be returned.

As a slight bonus, the items will be returned in the order they appear in
the second list. (Which gives me an idea how to save a further four strokes:
use pop instead of shift to return in the order they appear in the first
list.)



More information about the london.pm mailing list