Robbie Hatley’s Solutions, in Perl, for The Weekly Challenge #360 (“Text Justifier” and “Word Sorter”)
For those not familiar with "The Weekly Challenge", it is a weekly programming puzzle with two parts, with a new pair of tasks each Monday. You can find it here: The Weekly Challenge
The Weekly Challenge for the week of 2026-02-09 through 2026-02-15 is #360. The tasks for challenge #360 are as follows:
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Task 360-1: Text Justifier Submitted by: Mohammad Sajid Anwar You are given a string and a width. Write a script to return the string that centers the text within that width using asterisks * as padding. ( # Example #1 input: ["Hi", 5], # Expected output: "*Hi**" # Example #2 input: ["Code", 10], # Expected output: "***Code***" # Example #3 input: ["Hello", 9], # Expected output: "**Hello**" # Example #4 input: ["Perl", 4], # Expected output: "Perl" # Example #5 input: ["A", 7], # Expected output: "***A***" # Example #6 input: ["", 5] # Expected output: "*****" );
To solve this, just compute the left and right pad widths, then do:
$out = '*'x$lpw . $str . '*'x$rpw
Robbie Hatley's Perl Solution to The Weekly Challenge 360-1
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Task 360-2: Word Sorter Submitted by: Mohammad Sajid Anwar You are given a sentence. Write a script to order words in the given sentence alphabetically but keeps the words themselves unchanged. # Example #1 input: "The quick brown fox", # Expected output: "brown fox quick The" # Example #2 input: "Hello World! How are you?", # Expected output: "are Hello How World! you?" # Example #3 input: "Hello", # Expected output: "Hello" # Example #4 input: "Hello, World! How are you?", # Expected output: "are Hello, How World! you?" # Example #5 input: "I have 2 apples and 3 bananas!" # Expected output: "2 3 and apples bananas! have I"
To solve this problem, I'll split the sentence on /\s+/ to form a list of "words", case-insensitively sort those words with "sort {fc $a cmp fc $b}", paste with "join ' ',", and return result.
Robbie Hatley's Perl Solution to The Weekly Challenge 360-2
That's it for challenge 360; see you on challenge 361!
Comments
Post a Comment