Robbie Hatley's Solutions To The Weekly Challenge #215

For those not familiar with "The Weekly Challenge", it is a weekly programming puzzle, usually with two parts, cycling every Sunday. You can find it here:

The Weekly Challenge

This week (2023-04-30 through 2023-05-06) is weekly challenge #215.

Task 1 is as follows:

"You are given a list of words (alphabetic characters only) of same size. Write a script to remove all words not sorted alphabetically and print the number of words in the list that are not alphabetically sorted."

I found the solution easy, just a matter of determining which words are "sorted" by comparing each $word to join(sort(split($word))), like so:

Robbie Hatley's Perl Solution to The Weekly Challenge 215-1

Task 2 is as follows:

"You are given a list of numbers having just 0 and 1. You are also given placement count (>=1). Write a script to find out if it is possible to replace 0 with 1 the given number of times in the given list. The only condition is that you can only replace when there is no 1 on either side. Print 1 if it is possible otherwise 0."

Conceptually, this is even simpler than Task 1: Just replace what we can, keep tally, and if tally >= $count, print 1, else 0. But in-practice, there is the annoying matter of "special cases": Arrays of sizes 0,1,2 and the 0th and last elements of every array. Those all need to be handled separately, so it's not just a case of writing a sub and applying it to every element of an array using a for loop. In fact, I ended up using NO subs but a disgusting number of "if" statements to handle the special cases:

Robbie Hatley's Perl Solution to The Weekly Challenge 215-2

That's it for 215; see you on 216!

Comments

Popular posts from this blog

Robbie Hatley's Solutions To The Weekly Challenge #221

Robbie Hatley's Solutions To The Weekly Challenge #239