Robbie Hatley's Solutions To The Weekly Challenge #242

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-11-05 through 2023-11-11) is weekly challenge #242.

Task 242-1: Missing Members
Submitted by: Mohammad S Anwar
Given two arrays of integers, write a script to find the [unique]
members of each array which are missing in the other array.

Example 1:
Input:  @arr1 = (1, 2, 3); @arr2 = (2, 4, 6);
Output: ([1, 3], [4, 6])
(1, 2, 3) has 2 members (1, 3) missing in the array (2, 4, 6).
(2, 4, 6) has 2 members (4, 6) missing in the array (1, 2, 3).

Example 2:
Input:  @arr1 = (1, 2, 3, 3); @arr2 = (1, 1, 2, 2);
Output: ([3], [])
(1, 2, 3, 3) has 2 members (3, 3) missing in the array
(1, 1, 2, 2). Since they are same, keep just one.
(1, 1, 2, 2) has 0 members missing in the array (1, 2, 3, 3).

The original problem description didn't specify the word [unique], but Example 2 makes it clear that we are looking for unique (no repeats) members of each array which are missing in the other. So I'll first make "unique" versions of each array by using the "uniq" function from List::Util and the built-in "sort" function:

use List::Util 'uniq';
@unique1 = uniq sort @arr1;
@unique2 = uniq sort @arr2;

Then I'll just see which elements of @unique1 aren't in @unique2 and vice-versa. I'll make subs "is_int", "are_ints", "is_in", and "missing" to do most of the work, then call these from the main array loop:

Robbie Hatley's Solution to The Weekly Challenge 242-1

Task 242-2: Flip Matrix
Submitted by: Mohammad S Anwar
Given n x n binary matrix, write a script to flip
the given matrix as below:
1 1 0
0 1 1
0 0 1
a) Reverse each row
0 1 1
1 1 0
1 0 0
b) Invert each member
1 0 0
0 0 1
0 1 1

Example 1:
Input:  ([1, 1, 0], [1, 0, 1], [0, 0, 0])
Output: ([1, 0, 0], [0, 1, 0], [1, 1, 1])

Example 2:
Input:  ([1, 1, 0, 0], [1, 0, 0, 1], [0, 1, 1, 1], [1, 0, 1, 0])
Output: ([1, 1, 0, 0], [0, 1, 1, 0], [0, 0, 0, 1], [1, 0, 1, 0])

Reversing the rows is easily done with "reverse", and logically-inverting the elements can be done with "!". However, instead of doing that, I think I'll use a combined approach using ranged "for", "!", and "unshift":

Robbie Hatley's Solution to The Weekly Challenge 242-2

That's it for 242; see you on 243!

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