Hello, o wise ones.

Disclaimer in advance: This is homework. The task is to determine whether a list is a sublist of another (sub in_list()). Order matters, these are real lists, not sets. I coded a solution, see below.

Can you think of any other approaches, possibly simpler and without using LCS?

use Test::More tests => 6; use List::MoreUtils qw(each_arrayref); use Algorithm::Diff qw(LCS); sub _identic { # Returns true is two lists are identic. my ($lsa, $lsb) = @_; return unless scalar @{$lsa} == scalar @{$lsb}; # bail if unequ +al length my $iterator = each_arrayref($lsa, $lsb); while (my ($first, $second) = $iterator->()) { return unless $first eq $second; # bail if two elements at the same position differ } # at here, all elements are pairwise identic return 1; } sub in_list { # Returns true if lsa is a proper subsequence of lsb my ($lsa, $lsb) = @_; my $LCS = LCS($lsa, $lsb); return _identic($LCS, $lsa); } my (@lsa, @lsb); @lsa = (1, 2, 3); @lsb = (1, 2, 3, 4, 5); ok in_list(\@lsa, \@lsb), 'partial list at start'; @lsa = (1, 2, 3); @lsb = (2, 1, 2, 3); ok in_list(\@lsa, \@lsb), 'partial list at end'; @lsa = (1, 2, 3); @lsb = (3, 2, 1); ok !in_list(\@lsa, \@lsb), 'same elements, but nothing in common due t +o order'; @lsa = (); @lsb = (); ok in_list(\@lsa, \@lsb), 'null list, identic'; @lsa = (1); @lsb = (2); ok !in_list(\@lsa, \@lsb), 'single element, different'; @lsa = (1); @lsb = (1); ok in_list(\@lsa, \@lsb), 'single element, identic';

In reply to sublist of a list by Anonymous Monk

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.