Robbie Hatley's Solutions, in Perl, for The Weekly Challenge #308 ("Count Common" and "Decode XOR")
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 for the week of 2025-02-10 through 2025-02-16 is #308.
The tasks for challenge #308 are as follows:
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Task 308-1: Count Common Submitted by: Mohammad Sajid Anwar You are given two array of strings, @str1 and @str2. Write a script to return the count of common strings in both arrays. Example #1: Input: @str1 = ("perl", "weekly", "challenge") @str2 = ("raku", "weekly", "challenge") Output: 2 Example #2: Input: @str1 = ("perl", "raku", "python") @str2 = ("python", "java") Output: 1 Example #3: Input: @str1 = ("guest", "contribution") @str2 = ("fun", "weekly", "challenge") Output: 0
For each set of strings I'll make a hash counting occurrences. Then I'll make a (sorted, deduped) "combined" string set from the two originals. Then I'll push any element of @combined which has greater-than-zero occurrences in both original string sets to an array "@common" and return that.

Robbie Hatley's Perl Solution to The Weekly Challenge 308-1
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Task 308-2: Decode XOR Submitted by: Mohammad Sajid Anwar You are given an encoded array and an initial integer. Write a script to find the original array that produced the given encoded array. It was encoded such that encoded[i] = orig[i] XOR orig[i + 1]. Example #1: Input: @encoded = (1, 2, 3), $initial = 1 Output: (1, 0, 2, 1) Encoded array created like below, if the original array was (1, 0, 2, 1) $encoded[0] = (1 xor 0) = 1 $encoded[1] = (0 xor 2) = 2 $encoded[2] = (2 xor 1) = 3 Example #2: Input: @encoded = (6, 2, 7, 3), $initial = 4 Output: (4, 2, 0, 7, 4)
Though the problem description does not specify whether "XOR" refers to "logical XOR" or "bit-wise XOR", the examples make it clear that "XOR" means "the decimal representation of the bit-wise XOR of the binary representations of two small non-negative decimal integers". I say "small" and "non-negative" because otherwise there is no unambiguous meaning to Perl expression "$a ^ $b". So I'll make the stipulation in my program that all numbers involved must be "small non-negative integers in the closed interval [0,255]". In that case, if we let $c = $a ^ $b, then $c ^ $b == $a and $c ^ $a == $b, by the rules of how "XOR" works. So, given the initial (index 0) element of the original, we can then easily recreate the rest of the original by letting each subsequent $orig[i] = $orig[i-1] ^ $encoded[i-1].

Robbie Hatley's Perl Solution to The Weekly Challenge 308-2
That's it for challenge 308; see you on challenge 309!
Comments
Post a Comment