BUU has asked for the wisdom of the Perl Monks concerning the following question:

I was playing around with this golf in #perl irc channel the other day and I was wondering if anyoen had any brilliant ideas to better my current solution. The goal is simple, write a sub that finds the number of elements of @y that match elements in @x. Repeated elements in either can be ignored, that is, if @y has "A", "A", and @x has "A", you only need to report one match. @x and @y may be globals so initialization won't count for your strokes, same with the sub boilerplate.

My best is 28 strokes, can you do better?

Replies are listed 'Best First'.
Re: Perl Golf-- testing array intersection
by GrandFather (Saint) on Jan 30, 2006 at 21:26 UTC

    Not only does it return an incorrect result, it contains a gratuitous space. Prepending "scalar " to the code fixes the result and with the extra space removed gives a 34 stroke solution. There is a 29 stroke solution that gives the correct result.


    DWIM is Perl's answer to Gödel

      Prepending 0+ also fixes the context issue but is 4 characters shorter than “scalar”.

      Makeshifts last the longest.

        Spoiler :) Actually 5 strokes shorter because scalar requires a space after it before the grep.


        DWIM is Perl's answer to Gödel
Re: Perl Golf-- testing array intersection
by Errto (Vicar) on Jan 30, 2006 at 21:21 UTC
    27 unless I'm making some mistake:
    sub match { # 123456789012345678901234567 ++$c{$_}for@x;grep$c{$_},@y }
    Note that this assumes the sub will be called in scalar context
Re: Perl Golf-- testing array intersection
by Aristotle (Chancellor) on Jan 30, 2006 at 21:30 UTC

    Both your and Errto’s solutions violate your spec: they will ignore duplicate elements in @x, but they report duplicate matches in @y.

    The best I’ve come up with that works correctly is 49 characters (or 51 if you care about the context issue).

    Makeshifts last the longest.

Re: Perl Golf-- testing array intersection
by GrandFather (Saint) on Jan 30, 2006 at 22:37 UTC
Re: Perl Golf-- testing array intersection
by martin (Friar) on Jan 31, 2006 at 02:42 UTC
Re: Perl Golf-- testing array intersection
by samtregar (Abbot) on Jan 30, 2006 at 21:16 UTC
    Your sub returns a list of 1s, which doesn't seem correct to me.

    -sam

      In scalar context, it does return the number of 1s, which is what he wants.

      Makeshifts last the longest.

Re: Perl Golf-- testing array intersection
by thundergnat (Deacon) on Jan 31, 2006 at 01:00 UTC

    Hmmm.... 25 if you can't have duplicate values in the second array. 39 if you can.

    (if it is allowed to return a list, 23 and 37. Remove 0+ from each.)