diff options
| author | Matthias Muth <matthias.muth@gmx.de> | 2024-10-07 17:27:50 +0200 |
|---|---|---|
| committer | 冯昶 <fengchang@novel-supertv.com> | 2024-10-08 09:56:24 +0800 |
| commit | 28829b22b96e687efad57b2f7ccd80be61d0aef0 (patch) | |
| tree | 2f0cf4daa5b5a5a9f0ae548dcf1aea94a2e9fa5c /challenge-289 | |
| parent | 39e08d8fc0f815e8d36c493c37f4db5f68fe3ef3 (diff) | |
| download | perlweeklychallenge-club-28829b22b96e687efad57b2f7ccd80be61d0aef0.tar.gz perlweeklychallenge-club-28829b22b96e687efad57b2f7ccd80be61d0aef0.tar.bz2 perlweeklychallenge-club-28829b22b96e687efad57b2f7ccd80be61d0aef0.zip | |
Challenge 289 Task 1 and 2 solutions in Perl by Matthias Muth - Update
Diffstat (limited to 'challenge-289')
| -rwxr-xr-x | challenge-289/matthias-muth/perl/ch-2.pl | 38 |
1 files changed, 34 insertions, 4 deletions
diff --git a/challenge-289/matthias-muth/perl/ch-2.pl b/challenge-289/matthias-muth/perl/ch-2.pl index f86c3e78ba..44cc388bc7 100755 --- a/challenge-289/matthias-muth/perl/ch-2.pl +++ b/challenge-289/matthias-muth/perl/ch-2.pl @@ -10,14 +10,42 @@ use v5.36; -use utf8; -binmode(STDOUT, ":utf8"); - +# Fisher-Yates shuffle (or Knuth shuffle). sub jumble_string( $str ) { my @chars = split "", $str; return join "", map { splice @chars, rand( @chars ), 1, () } 0..$#chars; } +# Modern version (Durstenfeld shuffle). +sub jumble_string( $str ) { + my @chars = split "", $str; + for my $i ( reverse 0..$#chars ) { + my $j = rand( $i + 1 ); + ( $chars[$i], $chars[$j] ) = ( $chars[$j], $chars[$i] ); + } + return join "", @chars; +} + +# Modern version (Durstenfeld shuffle). +sub jumble_string( $str ) { + my @chars = split "", $str; + for my $i ( reverse 0..$#chars ) { + my $j = rand( $i + 1 ); + ( $chars[$i], $chars[$j] ) = ( $chars[$j], $chars[$i] ); + } + return join "", @chars; +} + +# Durstenfeld shuffle directly on characters. +sub jumble_string( $str ) { + for my $i ( reverse 0 .. length( $str ) - 1 ) { + my $j = rand( $i + 1 ); + ( substr( $str, $i, 1 ), substr( $str, $j, 1 ) ) = + ( substr( $str, $j, 1 ), substr( $str, $i, 1 ) ); + } + return $str; +} + sub jumbled_letters( $str ) { return $str =~ s{ (?<=[A-Za-z]) [a-z]+ (?=[a-z]) @@ -27,7 +55,9 @@ sub jumbled_letters( $str ) { } use Test2::V0 qw( -no_srand ); -use Data::Dump qw( pp ); + +use utf8; +binmode(STDOUT, ":utf8"); my $input_text = <<EOF; According to a researchch at Cambridge University, it doesn’t matter in what |
