January 2021 Archives

Perl weekly challenge 97

Here are solutions to this weeks challenges from the Perl Weekly Challenge.

You can find my full code on Github

Challenge 1

You are given string $S containing alphabets A..Z only and a number $N. Write a script to encrypt the given string $S using Caesar Cipher with left shift of size $N.

Solution


sub caesar {
  return $_[0]…

Perl weekly challenge 96

This week we had contrasting challenges.

Challenge 1 - Reverse Words

Take a string of words {with arbitrary white space around the words} and reverse the order of the words in the string and removing any redundant white space.

This is a classic example of a 1-liner....


   join q( ), reverse grep {$_} split m{\s+}, $_[0];

Challenge 2 - Edit Distance

I will provide 2 solutions here... one a less optimal solution which at the same time gives us a nice way of rendering the alignment - and then an more effic…

Perl weekly challenge 95

Palindromic numbers

You are given a number $N. Write a script to figure out if the given number is Palindrome. Print 1 if true otherwise 0.

There is an easy solution to this - to use "reverse" in string context to reverse the number and comparing the two strings:


sub is_palindrome_rev {
  return ( $_[0] eq reverse $_[0]) ? 1 : 0;
}

But this just seems a touch too easy - so let's see if we can find an alternative solution. Something that will potentially work in any base - not just base 10…

Perl weekly challenge 94

The two challenges this week were a nice introduction to the new year.

Challenge 1 - Group words into groups of anagrams.

This is a nice hash or "arrayref"s question - a Perl staple. For each group we need to generate a key, and put every anagram into this bin.

The simplest key is just to sort the letters into alphabetical order:

join q(), sort split m{}

This means the meat of the method can be written as a one liner.

sub group_anagrams {
  my $anagrams = {};
  push @{ $anagrams-…

About James Curtis-Smith

user-pic Perl developer for nearly 30 years now, mainly in maintenance scripts and web pages, using mod_perl. I also code a lot in PHP (20+yrs), and also extensive experience in HTML (27+yrs), Javascript(25+yrs), CSS (24+yrs) and SASS.