Robbie Hatley's Solutions To The Weekly Challenge #248

For those not familiar with "The Weekly Challenge", it is a weekly programming puzzle with two parts, cycling every Sunday. You can find it here:

The Weekly Challenge

This week (2023-12-17 through 2023-12-24) is weekly challenge #248. Its tasks are as follows:

Task 248-1: Shortest Distance
Submitted by: Mohammad S Anwar
Rephrased by: Robbie Hatley
Given a string and a character in the given string, write a
script to return the array of distances abs(i-j) between each
index of the string and the index of the nearest copy of the
given character within the string, or print an error message
if the input is invalid.

Example 1:
Input: $str = "loveleetcode", $char = "e"
Output: (3,2,1,0,1,0,0,1,2,2,1,0)

Example 2:
Input: $str = "aaab", $char = "b"
Output: (3,2,1,0)

This can be easily solved by using a pair of nested 3-part loops. The outer loop (over variable i) will look at each index of the string, and the inner loop (over variable j) will look for the given character in the string at distances starting from 0 and working up towards len($str), adding the first (and hence smallest) distance found to the array of distances.

I'll also write a stipulation into the main loop that rejects any [string, character] pair that is malformed (ref($array) neq 'ARRAY', or scalar(@$array) != 2, or len($str) < 1, or len($chr) != 1, or $str !~ /$chr/).

Robbie Hatley's Perl Solution to The Weekly Challenge 248-1

Task 248-2: Submatrix Sum
Submitted by: Jorg Sommrey
Rephrased by: Robbie Hatley
Given a NxM matrix A of real numbers, write a script to construct
an (N-1)x(M-1) matrix B having elements that are the sum over the
2x2 submatrices of A,
b[i,k] = a[i,k] + a[i,k+1] + a[i+1,k] + a[i+1,k+1]

Example 1:

Input:   [1,  2,  3,  4],
         [5,  6,  7,  8],
         [9, 10, 11, 12]

Output:  [14, 18, 22],
         [30, 34, 38]

Example 2:

Input:   [1, 0, 0, 0],
         [0, 1, 0, 0],
         [0, 0, 1, 0],
         [0, 0, 0, 1]

Output:  [2, 1, 0],
         [1, 2, 1],
         [0, 1, 2]

The solution to task 248-2 is similar to that of 248-1, because we need only make an array of matrices of numbers, then iterate over each mxn matrix with nested 3-part loops to make the smaller m-1xn-1 matrix of the sums of the 2x2 subarrays of the original matrix.

Robbie Hatley's Perl Solution to The Weekly Challenge 248-2

That's it for 248; see you on 249!

Comments

Popular posts from this blog

Robbie Hatley's Solutions To The Weekly Challenge #221

Robbie Hatley's Solutions To The Weekly Challenge #239

Robbie Hatley's Solutions To The Weekly Challenge #262