diff options
| author | KjetilS <kjetilskotheim@gmail.com> | 2025-07-03 15:45:27 +0200 |
|---|---|---|
| committer | KjetilS <kjetilskotheim@gmail.com> | 2025-07-03 15:45:27 +0200 |
| commit | d104b1fc88f9f3d6cf3e4a720bb16b40358363b3 (patch) | |
| tree | cafa9da62c914d1f87ab867afb2d845cbcc7d13b | |
| parent | 4ad759fd526ff799af698145651e5f9554aedaad (diff) | |
| download | perlweeklychallenge-club-d104b1fc88f9f3d6cf3e4a720bb16b40358363b3.tar.gz perlweeklychallenge-club-d104b1fc88f9f3d6cf3e4a720bb16b40358363b3.tar.bz2 perlweeklychallenge-club-d104b1fc88f9f3d6cf3e4a720bb16b40358363b3.zip | |
https://theweeklychallenge.org/blog/perl-weekly-challenge-328/
| -rw-r--r-- | challenge-328/kjetillll/perl/ch-1.pl | 49 | ||||
| -rw-r--r-- | challenge-328/kjetillll/perl/ch-2.pl | 16 |
2 files changed, 65 insertions, 0 deletions
diff --git a/challenge-328/kjetillll/perl/ch-1.pl b/challenge-328/kjetillll/perl/ch-1.pl new file mode 100644 index 0000000000..a5b617eee5 --- /dev/null +++ b/challenge-328/kjetillll/perl/ch-1.pl @@ -0,0 +1,49 @@ +sub f { + local $_ = pop; + 1 while s{ + (.?) + \? + (.?) + } + { + $1 + . + ( grep /[^$1$2 ]/, 'a' .. 'z' )[0] + . + $2 + }ex; + $_; +} + + +print f("a?z") eq "abz" ? "ok" : "err", "\n"; +print f("pe?k") eq "peak" ? "ok" : "err", "\n"; +print f("gra?te") eq "grabte" ? "ok" : "err", "\n"; +print f("a?????b") eq "ababacb" ? "ok" : "err", "\n"; +print f("?a?") eq "bab" ? "ok" : "err", "\n"; +print f("?") eq "a" ? "ok" : "err", "\n"; + +__END__ + +For speedup, should it be needed, on very long inputs with many '?' chars +and/or very many inputs, initialize once an @array or a %hash and replace +this construct: + +( grep /[^$1$2 ]/, 'a' .. 'z' )[0] + +with either this: + +$array[ ord($1||'a') ][ ord($2||'a') ] + +or this: + +$array[ ord($1||'a') * 128 + ord($2||'a') ] + +or this if you prefer hashes and accept a little slower lookup than arrays: + +$hash{ $1 || 'a', $2 || 'a' } + +where the array/hash contains a possible pre-calculated letter for all +26*26=676 possible combinations of the two a-z chars before and after the '?' +and default to 'a' if the '?' are at the beginning or end of the string. + diff --git a/challenge-328/kjetillll/perl/ch-2.pl b/challenge-328/kjetillll/perl/ch-2.pl new file mode 100644 index 0000000000..fb88fd4616 --- /dev/null +++ b/challenge-328/kjetillll/perl/ch-2.pl @@ -0,0 +1,16 @@ +use v5.10; + +sub f { + state $regex_list = join '|', map { uc.lc, lc.uc } 'a' .. 'z'; #Aa|aA|Bb|bB ... Zz|zZ + my $str = shift; + 1 while $str =~ s/$regex_list//g; + $str +} + + +print f( "WeEeekly" ) eq "Weekly" ? "ok\n" : "err\n"; +print f( "abBAdD" ) eq "" ? "ok\n" : "err\n"; +print f( "abc" ) eq "abc" ? "ok\n" : "err\n"; + +#'state' instead of 'my' inits $regex_list only once even though f() is called multiple times. +#It also makes $regex_list invisible outside of sub f. Needs at least 'v5.10' for 'state' to be available. |
