Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:
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';
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: sublist of a list
by Corion (Patriarch) on Nov 02, 2008 at 16:20 UTC | |
by Anonymous Monk on Nov 02, 2008 at 17:02 UTC | |
|
Re: sublist of a list
by ikegami (Patriarch) on Nov 02, 2008 at 21:14 UTC | |
|
Re: sublist of a list
by kyle (Abbot) on Nov 02, 2008 at 21:18 UTC | |
by ikegami (Patriarch) on Nov 02, 2008 at 21:35 UTC | |
|
Re: sublist of a list
by dragonchild (Archbishop) on Nov 03, 2008 at 12:45 UTC |