diff options
| author | Mohammad Sajid Anwar <Mohammad.Anwar@yahoo.com> | 2025-10-06 19:35:00 +0100 |
|---|---|---|
| committer | GitHub <noreply@github.com> | 2025-10-06 19:35:00 +0100 |
| commit | 3d2ea83da437a389f330b3c9a14fe48c54f98340 (patch) | |
| tree | 89e9e11c99ad9ea4f6331a4f996acb314d099cd7 | |
| parent | f45f28737b6311765d7be67429703e373e5aaead (diff) | |
| parent | 96232c9d631d7c39038fca0c09bfe970351c3c17 (diff) | |
| download | perlweeklychallenge-club-3d2ea83da437a389f330b3c9a14fe48c54f98340.tar.gz perlweeklychallenge-club-3d2ea83da437a389f330b3c9a14fe48c54f98340.tar.bz2 perlweeklychallenge-club-3d2ea83da437a389f330b3c9a14fe48c54f98340.zip | |
Merge pull request #12797 from ash/ash-342
Task 1 of Week 342, Raku by @ash
| -rw-r--r-- | challenge-342/ash/raku/ch-1.raku | 30 |
1 files changed, 30 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..c02e41c892 --- /dev/null +++ b/challenge-342/ash/raku/ch-1.raku @@ -0,0 +1,30 @@ +# 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. + return '' if (@digits.elems - @letters.elems).abs > 1; + + # Assuming that alphabetical sort puts digits first + return [~] (@digits Z~ @letters) if @digits.elems == @letters.elems; + + # Now the two cases where the size is different, but the + # difference of sizes is always 1 here. So appending the extra character. + return ([~] (@digits Z~ @letters)) ~ @digits[*-1] if @digits.elems > @letters.elems; + + return ([~] (@letters Z~ @digits)) ~ @letters[*-1]; +} |
