diff options
| author | E. Choroba <choroba@matfyz.cz> | 2025-05-19 08:59:47 +0200 |
|---|---|---|
| committer | E. Choroba <choroba@matfyz.cz> | 2025-05-19 08:59:47 +0200 |
| commit | c9942108fa3fe7a7449691f81e12c69ffc3b1520 (patch) | |
| tree | 7bc0d89f519901de7c0eff6d04f1dd7fae748abe | |
| parent | 6c467a026c325f27386294744ad5d0456d6c1c50 (diff) | |
| download | perlweeklychallenge-club-c9942108fa3fe7a7449691f81e12c69ffc3b1520.tar.gz perlweeklychallenge-club-c9942108fa3fe7a7449691f81e12c69ffc3b1520.tar.bz2 perlweeklychallenge-club-c9942108fa3fe7a7449691f81e12c69ffc3b1520.zip | |
Add solutions to 322: String Format & Rank Array by E. Choroba
| -rwxr-xr-x | challenge-322/e-choroba/perl/ch-1.pl | 22 | ||||
| -rwxr-xr-x | challenge-322/e-choroba/perl/ch-2.pl | 20 |
2 files changed, 42 insertions, 0 deletions
diff --git a/challenge-322/e-choroba/perl/ch-1.pl b/challenge-322/e-choroba/perl/ch-1.pl new file mode 100755 index 0000000000..78137a1355 --- /dev/null +++ b/challenge-322/e-choroba/perl/ch-1.pl @@ -0,0 +1,22 @@ +#!/usr/bin/perl +use warnings; +use strict; +use experimental qw( signatures ); + +sub string_format($str, $i) { + $str =~ tr/-//d; + my $mod = length($str) % $i; + $str =~ s/(?<=^.{$mod})/-/ if $mod && $mod != length $str; + + $str =~ /-/g; # Set pos to the dash (if any). + return $str =~ s/\G(.{$i})(?=.)/$1-/rg; # Separate groups of size $i. +} + +use Test::More tests => 3 + 2; + +is string_format('ABC-D-E-F', 3), 'ABC-DEF', 'Example 1'; +is string_format('A-BC-D-E', 2), 'A-BC-DE', 'Example 2'; +is string_format('-A-B-CD-E', 4), 'A-BCDE', 'Example 3'; + +is string_format('A-B', 15), 'AB', 'Single group'; +is string_format("", 2), "", 'Empty string'; diff --git a/challenge-322/e-choroba/perl/ch-2.pl b/challenge-322/e-choroba/perl/ch-2.pl new file mode 100755 index 0000000000..3ee6ffa9cc --- /dev/null +++ b/challenge-322/e-choroba/perl/ch-2.pl @@ -0,0 +1,20 @@ +#!/usr/bin/perl +use warnings; +use strict; +use experimental qw( signatures ); + +use List::Util qw{ uniq }; + +sub rank_array(@ints) { + my @uniq = sort { $a <=> $b } uniq(@ints); + my %rank; + @rank{@uniq} = 1 .. @uniq; + return @rank{@ints} +} + +use Test2::V0; +plan(3); + +is [rank_array(55, 22, 44, 33)], [4, 1, 3, 2], 'Example 1'; +is [rank_array(10, 10, 10)], [1, 1, 1], 'Example 2'; +is [rank_array(5, 1, 1, 4, 3)], [4, 1, 1, 3, 2], 'Example 3'; |
