diff options
| author | Alexander Pankoff <ccntrq@screenri.de> | 2021-02-13 14:25:17 +0100 |
|---|---|---|
| committer | Alexander Pankoff <ccntrq@screenri.de> | 2021-02-13 15:17:29 +0100 |
| commit | 943525c28b69ffeaa7a0a8512eaa53c4ae6929bd (patch) | |
| tree | b46b508d48d4d8099c603641b04ddd6a5211fa6e /challenge-099 | |
| parent | 12ddbba805a4ba990e37b593041c445bbae2135b (diff) | |
| download | perlweeklychallenge-club-943525c28b69ffeaa7a0a8512eaa53c4ae6929bd.tar.gz perlweeklychallenge-club-943525c28b69ffeaa7a0a8512eaa53c4ae6929bd.tar.bz2 perlweeklychallenge-club-943525c28b69ffeaa7a0a8512eaa53c4ae6929bd.zip | |
add perl solution for wk-099 ch-2
reading through @jacoby 's blog post helped me a lot:
https://jacoby.github.io/2021/02/11/london-patterns-perl-weekly-challenge-99.html
Diffstat (limited to 'challenge-099')
| -rwxr-xr-x | challenge-099/alexander-pankoff/perl/ch-2.pl | 63 |
1 files changed, 63 insertions, 0 deletions
diff --git a/challenge-099/alexander-pankoff/perl/ch-2.pl b/challenge-099/alexander-pankoff/perl/ch-2.pl new file mode 100755 index 0000000000..aeeea3c9ef --- /dev/null +++ b/challenge-099/alexander-pankoff/perl/ch-2.pl @@ -0,0 +1,63 @@ +#!/usr/bin/env perl +use v5.20; +use utf8; +use strict; +use warnings; +use feature qw(say signatures); +no warnings 'experimental::signatures'; + +{ + if ( $ENV{TESTING} ) { + test_count_subsequences(); + } + else { + my ( $S, $T ) = @ARGV; + die "usage: $0 STRING STRING\n" unless @ARGV == 2; + + say count_subsequences( $S, $T ); + } +} + +sub test_count_subsequences() { + + my @test_cases = ( [ "littleit", "lit", 5 ], [ "london", "lon", 3 ], ); + + require Test::More; + Test::More->import( tests => scalar @test_cases ); + + for my $test (@test_cases) { + my ( $string, $target, $count ) = @{$test}; + ok( + count_subsequences( $string, $target ) == $count, + "$string contains $count subsequences matching $target" + ); + } +} +use List::Util qw(first); + +sub count_subsequences ( $string, $target, $string_position = 0, + $target_position = 0 ) +{ + return 0 if ( $string_position >= length($string) ); + + my $count = count_subsequences( $string, $target, $string_position + 1, + $target_position ); + + my $string_char = substr( $string, $string_position, 1 ); + my $target_char = substr( $target, $target_position, 1 ); + if ( $string_char eq $target_char ) { + if ( $target_position == length($target) - 1 ) { + $count += 1; + } + else { + $count += count_subsequences( + $string, $target, + $string_position + 1, + $target_position + 1 + ); + } + } + + return $count; +} + |
