Also if the lists are huge and a lot of the items only appear on one of the lists it may be better to filter out those "unique" elements before you start looking for matches. Of course you can't remove them completely, you have to keep a "marker" there that's not equal to any other element nor marker.

use strict; my @a = qw(fred bob joe jim ethfgh mary elaine foo bar bob foo too); my @b = qw(frank joe jim dfkjhgdkjfg mary bob srere dfhgerg wet sdfwer + mary); my (%seenA, %seenB); { my $i = 0; @seenA{@a}=undef; @seenB{@b}=undef; my $last = -1; @a = map {exists $seenB{$_} ? ($last = $_) : (defined($last) ? ($l +ast = undef) : ())} @a; my $last = -1; @b = map {exists $seenA{$_} ? ($last = $_) : (defined($last) ? ($l +ast = undef) : ())} @b; } print "@a\n"; print "@b\n\n"; shift(@a) unless defined $a[0]; shift(@b) unless defined $b[0]; pop(@a) unless defined $a[-1]; pop(@b) unless defined $b[-1]; print "@a\n"; print "@b\n\n"; my @result; while (@a and @a > @result) { my $start = 0; while (@b - $start > @result) { my $end = 0; my @maybe = (); $end++ while (defined($a[$end]) and defined($b[$start+$end]) a +nd $a[$end] eq $b[$start+$end]); if (--$end > @result) { @result = @a[0..$end]; } $start++; } shift(@a); } print "@result\n";

I assume the lists did not contain any undefs!

Jenda
Always code as if the guy who ends up maintaining your code will be a violent psychopath who knows where you live.
   -- Rick Osborne

Edit by castaway: Closed small tag in signature


In reply to Re: Re: Finding largest common subset in lists? by Jenda
in thread Finding largest common subset in lists? by anjiro

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.