Robbie Hatley's Solutions To The Weekly Challenge #278
For those not familiar with "The Weekly Challenge", it is a weekly programming puzzle with two parts, cycling every Sunday. You can find it here:
The Weekly Challenge for the week of 2024-07-14 through 2024-07-20 is #278. Its tasks are as follows:
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Task 278-1: Sort String Submitted by: Mohammad Sajid Anwar Given a shuffled string, write a script to return the sorted string. A string is shuffled by appending word position to each word. Example 1 input: "and2 Raku3 cousins5 Perl1 are4" Expected output: "Perl and Raku are cousins" Example 2 input: "guest6 Python1 most4 the3 popular5 is2 language7" Expected output: "Python is the most popular guest language" Example 3 input: "Challenge3 The1 Weekly2" Expected output: "The Weekly Challenge"
My approach was to do this:
- Split the string by whitespace to array of tokens "@raw_tok".
- Sort "@raw_tok" to array "@srt_tok" by unicode codepoint of the last character.
- Join with spaces a map of "@srt_tok" with the last character of each token removed.
But then I realized, I don't need any of the intermediates, and this is best written in reverse order, as a purely "functional" subroutine:
use v5.38; use utf8; sub sort_string ($string) { join ' ', map {substr $_, 0, length($_) - 1} sort {ord substr($a, -1, 1) <=> ord substr($b, -1, 1)} split /\s+/, $string }
Robbie Hatley's Perl Solution to The Weekly Challenge 278-1
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Task 278-2: Reverse Word Submitted by: Mohammad Sajid Anwar Given a word, $word and a character, $char, write a script to replace the substring up to and including $char with its characters sorted alphabetically. If $char doesn’t exist in $word then don't do anything. Example 1 input: ["challenge", "e"], Expected output: "acehllnge" Example 2 input: ["programming", "a"], Expected output: "agoprrmming" Example 3 input: ["champion", "b"], Expected output: "champion"
I solve this by using a programmatic substitution with a "minimal" quantifier "*?":
use v5.38; use utf8; sub sort_string ($string, $char) { $string =~ s{^(.*?$char)}{join '', sort split //, $1}er; }
Robbie Hatley's Perl Solution to The Weekly Challenge 278-2
That's it for challenge 278; see you on challenge 279!
Comments
Post a Comment