diff options
| author | Bob Lied <boblied+github@gmail.com> | 2025-05-20 22:28:43 -0500 |
|---|---|---|
| committer | Bob Lied <boblied+github@gmail.com> | 2025-05-20 22:28:43 -0500 |
| commit | f5b1c70c44d3ca226ac1f3121c00f6120022fcd5 (patch) | |
| tree | 5bffbecdc509d5c72245efec371f02607c50d2e2 | |
| parent | 91785bb2dcecfcd8c2b789d27367cceae0bcaf12 (diff) | |
| download | perlweeklychallenge-club-f5b1c70c44d3ca226ac1f3121c00f6120022fcd5.tar.gz perlweeklychallenge-club-f5b1c70c44d3ca226ac1f3121c00f6120022fcd5.tar.bz2 perlweeklychallenge-club-f5b1c70c44d3ca226ac1f3121c00f6120022fcd5.zip | |
Update task 1 with blog
| -rw-r--r-- | challenge-322/bob-lied/blog.txt | 1 | ||||
| -rw-r--r-- | challenge-322/bob-lied/perl/ch-1.pl | 42 |
2 files changed, 29 insertions, 14 deletions
diff --git a/challenge-322/bob-lied/blog.txt b/challenge-322/bob-lied/blog.txt new file mode 100644 index 0000000000..97cf564eb7 --- /dev/null +++ b/challenge-322/bob-lied/blog.txt @@ -0,0 +1 @@ +https://dev.to/boblied/pwc-322-string-format-33pd diff --git a/challenge-322/bob-lied/perl/ch-1.pl b/challenge-322/bob-lied/perl/ch-1.pl index 73e89b291c..6a3fb1d9c9 100644 --- a/challenge-322/bob-lied/perl/ch-1.pl +++ b/challenge-322/bob-lied/perl/ch-1.pl @@ -48,24 +48,38 @@ sub strFmtRE($str, $i) return $str =~ s/^-//r; } -sub strFmtSubstr($str, $i) +sub strFmtUnpack($str, $i) { - $str = reverse $str =~ s/-+//gr; - my $d = int( (length($str) - 0.5) / $i); + return scalar reverse join("-", unpack("(A$i)*", reverse $str =~ s/-//gr)); +} - for my $p ( map { $_ * $i } reverse 1 .. $d ) +sub strFmtShift($str, $i) +{ + my @in = split(//, $str =~ s/-//gr); + my $out; + + my $d = 0; + while ( @in ) { - substr($str, $p, 0, '-'); - $logger->debug("i=$i p=$p str=$str"); + $out .= pop @in; + $out .= '-' if ( ++$d % $i == 0 && @in ); } - return reverse $str; + return scalar reverse $out; } -sub strFmtUnpack($str, $i) +sub strFmtSubstr($str, $i) { - return scalar reverse join("-", unpack("(A$i)*", reverse $str =~ s/-//gr)); + $str =~ s/-//g; + my $out = substr($str, 0, length($str) % $i, ''); + while ( $str ne '' ) + { + $out .= '-' if ( $out ne '' ); + $out .= substr($str, 0, $i, ''); + } + return $out; } + sub runTest { use Test2::V0; @@ -82,14 +96,13 @@ sub runTest is( strFmtUnpack("A-BC-D-E" , 2), "A-BC-DE", "Example 2"); is( strFmtUnpack("-A-B-CD-E", 4), "A-BCDE", "Example 3"); + is( strFmtShift("ABC-D-E-F", 3), "ABC-DEF", "Example 1"); + is( strFmtShift("A-BC-D-E" , 2), "A-BC-DE", "Example 2"); + is( strFmtShift("-A-B-CD-E", 4), "A-BCDE", "Example 3"); + done_testing; } -# $ perl ch-1.pl -b 200000 -# Rate substr regex unpack -# substr 54054/s -- -54% -81% -# regex 117647/s 118% -- -58% -# unpack 281690/s 421% 139% -- sub runBenchmark($repeat) { use Benchmark qw/cmpthese/; @@ -101,5 +114,6 @@ sub runBenchmark($repeat) regex => sub { strFmtRE($str, $i) }, substr => sub { strFmtSubstr($str, $i) }, unpack => sub { strFmtUnpack($str, $i) }, + shift => sub { strFmtShift($str, $i) }, }); } |
