Hi everybody! Just doing the first weekly challenge task again this week. This week we're sorting a list of numbers and then checking whether the number matches the same position in the unsorted list. It's a very simple challenge and easily written in about 4 actual lines of clean code.
Here's the code:
#!/usr/bin/perl
use strict;
use v5.24;
my @sorted = sort @ARGV;
my $matches;
for (my $i = 0; $i <= $#ARGV; $i++) {$matches++ if $ARGV[$i] == $sorted[$i]}
say $matches // 0;
This obviously doesn't have any error-checking to make sure the values are integers, so they could be text that's sorted differently, but we're assuming the input is trustworthy. For anyone new to programming reading this, never assume user input is trustworthy. Always do your safety checks and sanitize inputs.
Very simply, we're making a sorted copy of the inputs to the script, initializing $matches, looping through both lists checking for identical values (for which we need an index counter, which is why we use the 3-part loop structure) and add to $matches if we find one. Then we print either the number of matches or 0 if we didn't find any. The // 0
is necessary just so it doesn't print an empty line if the variable is still uninitialized.
Hope to see you all again next week with the next weekly challenge! Join the challenges if you find them interesting to read about.
Top comments (0)