Ok, first thing's first. What you actually want is the Largest Common Contiguous Ordered Subset. And so I give you a somewhat terrible algorithm (STA).

sub find_flccos { my @a = @{$_[0]}; my @b = @{$_[1]}; my (%map,@curchk,@longest); foreach my $i (0 .. $#a) { # I decided to store this map so we don't repeat this # O(n) step if we come across the same letter again $map{$a[$i]} = [ grep $b[$_] eq $a[$i], (0 .. $#b) ] unless define +d $map{$a[$i]}; # ok, these are the indices in b where we should #start matching from foreach my $j (@{$map{$a[$i]}}) { @curchk = (); # make temporary indices my ($ti,$tj) = ($i,$j); # fill @curchk with the longest current match while ($ti < @a && $tj < @b && $a[$ti] eq $b[$tj]) { push @curchk, $a[$ti]; $ti++; $tj++; } # change the longest array if it is longer #than the one found previously @longest = @curchk if ($#curchk > $#longest); } } return @longest; } __DATA__ my (@a,@b,@c,@d,@e,@f); @a = qw( a a a a b c d ); @b = qw( a b c b a b a c a d ); @c = qw(fred bob joe jim mary elaine); @d = qw(frank joe jim mary bob); @e = @f = (); print join ",", find_flccos(\@a,\@b); print $/; print join ",", find_flccos(\@d,\@c); print $/; print join ",", find_flccos(\@e,\@f); print $/; OUTPUT: > perl flccos.pl a,b,c joe,jim,mary >

Hope this helps.

Update: Looked like a disgusting mess before I put the comments on multiple lines. Sry ;-)

antirice    
The first rule of Perl club is - use Perl
The
ith rule of Perl club is - follow rule i - 1 for i > 1


In reply to Re: Finding largest common subset in lists? by antirice
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.