exercism-perl5

Repository for my Perl 5 Exercism exercises
git clone git://git.samirparikh.com/exercism-perl5
Log | Files | Refs | README

commit d6eeb08ce21dc686446be15bd3967bf464d4f136
parent 1b881234def2a09fbf64865f959ab45e658aaa30
Author: Samir Parikh <noreply@samirparikh.com>
Date:   Wed, 22 Dec 2021 16:16:21 +0000

update Sublist.pm to provide correct solution

Diffstat:
Msublist/Sublist.pm | 32+++++++++++++++++---------------
1 file changed, 17 insertions(+), 15 deletions(-)

diff --git a/sublist/Sublist.pm b/sublist/Sublist.pm @@ -5,28 +5,30 @@ use v5.22; use Exporter qw<import>; our @EXPORT_OK = qw<compare_lists>; -sub a_within_b2 { - my ($a, $b) = @_; - my @a = @{$a}; - my @b = @{$b}; - foreach my $element (@a) { - return 0 unless (grep /^$element$/, @b); # grep needs expr that evaluates - # to true or false - } - return 1; -} - sub a_within_b { # assume @a <= @b my ($a, $b) = @_; my @a = @{$a}; my @b = @{$b}; # check to see if first element of @a is in @b + # @idx is array that stores all indexes of @b where first element of @a is in @b my @idx = grep { $b[$_] eq $a[0] } 0 .. $#b; - return 0 unless (@idx); - for (my $a_idx=1, my $b_idx=$idx[0]+1; $a_idx<=$#a; $a_idx++, $b_idx++) { - return 0 unless ($a[$a_idx] eq $b[$b_idx]); + return 0 unless (@idx); # first element of @a not found anywhere in @b + foreach my $i (@idx) { # loop through each index of @b we found + # skip if the first element of @a occurs too near the end of @b + # (i.e. the remaining elements of @a won't fit in @b) + next if ($i > scalar @b - scalar @a); + # $match counts number of matches of @a in @b. Start at 1 since we already + # know that the first element of @a was found in @b + my $match = 1; + # sequentially loop through remaining elements of @a to see if they + # appear in order in @b + for (my $a_idx=1, my $b_idx=$i+1; $a_idx<=$#a; $a_idx++, $b_idx++) { + $match++ if ($a[$a_idx] eq $b[$b_idx]); + } + # number of matches has to eqal number of elements in @a + return 1 if ($match == scalar @a); } - return 1; + return 0; } sub compare_lists {