diff options
| author | Andrew Shitov <mail@andreyshitov.com> | 2025-10-06 09:29:46 +0200 |
|---|---|---|
| committer | Andrew Shitov <mail@andreyshitov.com> | 2025-10-06 09:29:46 +0200 |
| commit | 0c79a079ca55e5e06e3bf693fb4c3e61b3b70c7c (patch) | |
| tree | 66ecbc4e48577d09b055ae1c3ee1692ced2bba9e | |
| parent | 19226ec8142e8e55790e09bb6059d6a16f20f437 (diff) | |
| download | perlweeklychallenge-club-0c79a079ca55e5e06e3bf693fb4c3e61b3b70c7c.tar.gz perlweeklychallenge-club-0c79a079ca55e5e06e3bf693fb4c3e61b3b70c7c.tar.bz2 perlweeklychallenge-club-0c79a079ca55e5e06e3bf693fb4c3e61b3b70c7c.zip | |
Task 1 of Week 342, Raku by @ash
| -rw-r--r-- | challenge-342/ash/raku/ch-1.raku | 36 |
1 files changed, 36 insertions, 0 deletions
diff --git a/challenge-342/ash/raku/ch-1.raku b/challenge-342/ash/raku/ch-1.raku new file mode 100644 index 0000000000..e7ad930581 --- /dev/null +++ b/challenge-342/ash/raku/ch-1.raku @@ -0,0 +1,36 @@ +# Task 1 of the Weekly Challenge 342 +# https://theweeklychallenge.org/blog/perl-weekly-challenge-342/#TASK1 + +say balance-string('a0b1c2'); # 0a1b2c +say balance-string('abc12'); # 0a1b2c +say balance-string('0a2b1c3'); # 0a1b2c3 +say balance-string('1a23'); # '' +say balance-string('ab123'); # 1a2b3 + +# Extra case with 3 letters and 3 digits +say balance-string('abc123'); # 1a2b3c + + +sub balance-string($s) { + my @digits = $s.comb(/\d/).sort; + my @letters = $s.comb(/<[a..z]>/).sort; + + # It's only possible to balance a string if + # the number of digits and letters differs by not more than 2. + if ((@digits.elems - @letters.elems).abs > 1) { + return ''; + } + elsif (@digits.elems == @letters.elems) { + # Assuming that alphabetical sort puts digits first + return [~] (@digits Z~ @letters); + } + + # Now the two cases where the size is different, but the + # difference of sizes is always 1 here. So appending the extra character. + elsif (@digits.elems > @letters.elems) { + return ([~] (@digits Z~ @letters)) ~ @digits[*-1]; + } + else { + return ([~] (@letters Z~ @digits)) ~ @letters[*-1]; + } +} |
