Hello everybody! Back this week for weekly challenge 215, where we look for unsorted words and sets of zeros. This week both challenges took me only about 10-15 minutes each. The usual disclaimer about an early post, so don't read spoilers if you want to do the challenge yourself.
Odd One Out
This one's a very simple task to print the number of words that are not alphabetically sorted. Here's the code:
#!/usr/bin/perl
use strict;
use v5.24;
my $removed = 0;
foreach (@ARGV) {if ($_ ne join('', sort(split(//, $_)))) {$removed++}}
say $removed;
It's that simple. We just make a variable to count the number of non-alphabetical words, then for each word in the list we split it, sort the letters, and see if the resulting word matches the word we're testing. If not, we add it to the count. 3 lines essentially, not including the boilerplate. It might be possible to make it look cleaner, but in this one it was so easy to make it compact that I didn't see a point in cleaning it up.
Number Placement
In this task, you're provided with a number of how many zeros you want to remove. We print out a binary value, 1 or 0, of whether it's possible to remove that many zeros. Technically we don't remove the zeros, we change them to 1, but it can only happen if the adjacent numbers are also zero. Here's the solution:
#!/usr/bin/perl
use strict;
use v5.24;
my $count = shift;
say 'You chose a count of 0, please provide a different count.' and exit if $count == 0;
say 'There are not enough elements, please provide more elements to replace.' and exit if @ARGV < 3;
for (my $i = 1; $i < $#ARGV - 1; $i++) {
if (!($ARGV[$i - 1] + $ARGV[$i] + $ARGV[$i + 1])) {$ARGV[$i] = 1 and $count--}
}
say ($count > 0 ? '0' : '1');
This one I decided to do a little error-checking on zero counts and not having at least 3 elements. Also, I take the count as the first argument provided. I iterate through the numbers provided with a cursor starting at the second position looping to the second to last. If the cursor and its adjacent numbers are all 0, then we switch the cursor element to 1 and subtract from the remaining number to be found. If we haven't found all of them by the time we're done we print a failure 0, and if we have we print a success 1.
That's it for this week! Have a good week everybody and I'll probably see you next week!
Top comments (0)