diff options
| author | Bob Lied <boblied+github@gmail.com> | 2023-12-17 21:46:09 -0600 |
|---|---|---|
| committer | Bob Lied <boblied+github@gmail.com> | 2023-12-17 21:46:09 -0600 |
| commit | 75e2e0e2044ec402e661607746312bda43d38d7b (patch) | |
| tree | 5207ccf7af1ddfd53bebcc15699161e75658c745 | |
| parent | 5e14bb89fcebf48966afd275e2bff8eb523fa6af (diff) | |
| download | perlweeklychallenge-club-75e2e0e2044ec402e661607746312bda43d38d7b.tar.gz perlweeklychallenge-club-75e2e0e2044ec402e661607746312bda43d38d7b.tar.bz2 perlweeklychallenge-club-75e2e0e2044ec402e661607746312bda43d38d7b.zip | |
PWC 248 Task 1 alternate solution using index
| -rw-r--r-- | challenge-248/bob-lied/perl/ch-1.pl | 28 |
1 files changed, 28 insertions, 0 deletions
diff --git a/challenge-248/bob-lied/perl/ch-1.pl b/challenge-248/bob-lied/perl/ch-1.pl index 4214acf1f2..2f18387091 100644 --- a/challenge-248/bob-lied/perl/ch-1.pl +++ b/challenge-248/bob-lied/perl/ch-1.pl @@ -58,6 +58,28 @@ sub shortest($str, $char) return \@dist; } +sub sd2($str, $char) +{ + my @dist; + for my $i ( 0 .. length($str)-1 ) + { + my $ahead = index($str, "$char", $i); + my $behind = rindex($str, "$char", $i); + + if ( $ahead < 0 && $behind < 0 ) + { + push @dist, undef; + } + else + { + $behind = $ahead if $behind == -1; + $ahead = $behind if $ahead == -1; + push @dist, min abs($i - $behind), abs($ahead - $i); + } + } + return \@dist; +} + sub runTest { use Test2::V0; @@ -68,5 +90,11 @@ sub runTest is( shortest("ab", 'x'), [undef, undef], "no x in str"); is( shortest("", 'x'), [], "empty string"); + is( sd2("loveleetcode", 'e'), [3,2,1,0,1,0,0,1,2,2,1,0], "Example 1"); + is( sd2("aaab", 'b'), [3,2,1,0], "Example 2"); + + is( sd2("ab", 'x'), [undef, undef], "no x in str"); + is( sd2("", 'x'), [], "empty string"); + done_testing; } |
