Perl Christmas Quiz

Fahad Khan fahad.a.khan at hotmail.com
Fri Dec 12 12:43:38 GMT 2008


> Date: Fri, 12 Dec 2008 12:10:19 +0000
> From: paulm at paulm.com
> To: london.pm at london.pm.org
> Subject: Re: Perl Christmas Quiz
> 
> SPOILERS contd

> 
> This isn't a set question though. Sets have unique membership,
> 
> stix:~$ perl -MSet::Scalar -le '$s = Set::Scalar->new(1,1); print $s->elements'
> 1
> 
> Something like,
> 
> sub intersect {
>   my @s1 = sort @{$_[0]};
>   my @s2 = sort @{$_[1]};
>   my @s3;
>   while (my $e = $s1[0]) {
>     if ($e == $s2[0]) {
>       push @s3, $e;
>       shift @s2;
>       shift @s1;
>     } elsif ($e > $s2[0]) {
>       shift @s2;
>     } else {
>       shift @s1;
>     }
>   }
>   @s3;
> }
> 
> There's probably some clever answer using List::MoreUtils.
> 
> P

In my baby perl.

sub intersect

{

    my ($a, $b) = @_;

    my ($c, $d) = ({}, []);

    foreach (@$a) { $c->{$_}->[0]++}

    foreach (@$b) { $c->{$_}->[1]++}



    while( my ($k, $v) = each %$c ) {

        my ($i, $j) = @$v;

        for(my $x=0; $x < ($i < $j ? $i : $j); $x++) {push @$d, $k}

    }
    return $d;

}


Fahad.

_________________________________________________________________
Imagine a life without walls.  See the possibilities. 
http://clk.atdmt.com/UKM/go/122465943/direct/01/


More information about the london.pm mailing list