PWC 185

PWC 185

Challenge 2 (Mask Code)

Given a list of arbitrary strings consisting of alphanumeric and other characters, we are asked to run a script that replaces the first four alphanumeric characters in each string with x. Thus (from the test example), 'ab-cde-123' gets converted to 'xx-xxe-123'.

This is a one-liner in Perl 5 and Raku. In Perl 5:

perl -E 'for my $test (@ARGV) {$test =~ s/[a-wyz0-9]/x/ for (1 .. 4); say $test}' 'ab-cde-123' '123.abc.420' '3abc-0010.xy'

I loop through the strings in ARGV and for each string loop four times through a substitution regex that finds the next alphanumeric that is not x and replaces it with x. 

The same logic in Raku:

raku -e '@*ARGS.map({my $temp=$_; ($temp ~~ s/<[a .. w y z 0 .. 9]>/x/) for (0 .. 3); say $temp;})' 'ab-cde-123' '123.abc.420' '3abc-0010.xy'

In Julia I do not use a one-liner and follow the Julia-ish approach of multiple dispatch, with a function mask() defined for an input string, and another version of mask() defined for a list of such strings. The list version of mask loops through the list calling the string version of mask for each list member.  

Here is my Julia script.  

The Julia replace function for string substitution is neat. It has an option to include a counter, say 4, to perform the substitution exactly four times. Exactly what we need for this task! 

Challenge 1 (MAC Address)

Given a MAC address in the format '1ac2.34f0.b1c2', we are asked to represent it in the format '1a:c2:34:f0:b1:c2'.

This could be a one-liner, but inspiration didn't strike, and I ended up with a straightforward multi-line script. 

I split the MAC address on /\./ into four-letter pieces, and then push each two-letter substring of each four-letter piece into an array. Finally, I join that array using ':'.

Same logic in all three languages.

Here is my Perl 5 script.

Here is my Raku script.

Here is my Julia script.  

Fellow contributor Jaldhar Vyas has a great regex-based one-liner for this, in both Perl 5 and Raku. He sets up a regex that captures each two-letter substring in the sequence, and then joins them using ':'. Now why didn't I think of that! Here is  his blog where he explains it.

Comments

Popular posts from this blog

PWC 215

PWC 227

PWC 234