PWC 189

PWC 189

Challenge 1 (Greater Character)

"You are given an array of characters (a..z) and a target character. Write a script to find out the smallest character in the given array lexicographically greater than the target character."

I sort the list. Then, in Perl 5 and Julia, I loop through the sorted elements until I hit one just bigger than the target. In Raku, I just use grep.

Here is the key snippet from my Raku script:

@arry.sort({$^a cmp $^b}).grep({$_ gt $target}).min;

Challenge 2 (Array Degree)

"You are given an array of 2 or more non-negative integers. Write a script to find out the smallest slice, i.e. contiguous subarray of the original array, having the degree of the given array."

The degree of the array is the maximum frequency with which any element occurs. Thus for the example given (1,3,3,2), the degree is 2 (the frequency of the most common or modal element 3).

The smallest slice with the same degree is the smallest slice containing every occurrence of the modal element. This would be the slice that starts with the first and ends with the last occurrence of the modal element: (3,3) in the above example.

There could be multiple modal elements, in which case there could be multiple slices returned.

For my Perl 5 script, I decided to restrict it to the core syntax inherited from Perl 4. I call a subroutine smallest_slice_with_same_degree that returns a list of strings, each of which is an expression of the form @arry[first_index .. last_index]. These have to be eval'd, so I also include a wrapper function print_smallest_slice, which evals and prints the output from smallest_slice_with_same_degree.

The Perl 5 script is fast, running the examples in around 0.007 seconds. This is not much slower than the executable from Ali Moradi's C program which ran in 0.002 seconds on my hardware.

My Raku and Julia scripts mimic the Perl 5 logic, but of course are more modern. The Raku script directly returns the list of slices (no pseudo-closure) as an array of arrays. The Julia script just prints the output directly from the subroutine rather than returning the value. Both scripts are slower than the Perl 5 script at around 0.46 seconds for Raku and around 0.86 seconds for Julia.

I enjoyed writing the Perl 5 script and found it easy and fast to write. Perl is designed to efficiently use flat lists and strings in solving puzzles. I often like looking for solutions that avoid more complicated data structures.

What works well for Perl does not work so well in Julia, though. Probably a different approach is called for in Julia, say using arrays instead of dictionaries.

Comments

Popular posts from this blog

PWC 215

PWC 227

PWC 234