From c9942108fa3fe7a7449691f81e12c69ffc3b1520 Mon Sep 17 00:00:00 2001 From: "E. Choroba" Date: Mon, 19 May 2025 08:59:47 +0200 Subject: Add solutions to 322: String Format & Rank Array by E. Choroba --- challenge-322/e-choroba/perl/ch-1.pl | 22 ++++++++++++++++++++++ challenge-322/e-choroba/perl/ch-2.pl | 20 ++++++++++++++++++++ 2 files changed, 42 insertions(+) create mode 100755 challenge-322/e-choroba/perl/ch-1.pl create mode 100755 challenge-322/e-choroba/perl/ch-2.pl 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'; -- cgit