The Weekly Challenge 308

Count Common and Decode XOR

Task 1: Count Common

Given two arrays of strings, return the count of common strings.

Example 1

Input: ("perl","weekly","challenge"), ("raku","weekly","challenge") Output: 2

Example 2

Input: ("perl","raku","python"), ("python","java") Output: 1

Example 3

Input: ("guest","contribution"), ("fun","weekly","challenge") Output: 0

Logic

Use a hash/set to track elements from the first array, then count matches from the second array. Remove matched elements to avoid duplicate counting.

Perl Solution

ch-1.pl

#!/usr/bin/perl use strict; use warnings; use Test::More tests => 3; sub count_common { my ($arr1_ref, $arr2_ref) = @_; my %common; foreach my $elem (@$arr1_ref) { $common{$elem} = 1; } my $count = 0; foreach my $elem (@$arr2_ref) { if (exists $common{$elem}) { $count++; delete $common{$elem}; } } return $count; } is(count_common(["perl","weekly","challenge"], ["raku","weekly","challenge"]), 2, "Ex1"); is(count_common(["perl","raku","python"], ["python","java"]), 1, "Ex2"); is(count_common(["guest","contribution"], ["fun","weekly","challenge"]), 0, "Ex3");

Python Solution

ch-1.py

def count_common(str1: list[str], str2: list[str]) -> int: return len(set(str1).intersection(str2))

Task 2: Decode XOR

Given an encoded array where encoded[i] = original[i] XOR original[i+1], and the first element of the original array, decode and return the original array.

Example 1

Input: encoded = [1,2,3], initial = 1 Output: [1, 0, 2, 1]

Example 2

Input: encoded = [6,2,7,3], initial = 4 Output: [4, 2, 0, 7, 4]

Logic

Since encoded[i] = original[i] XOR original[i+1], we can recover original[i+1] = original[i] XOR encoded[i]. Start with the given initial value and iteratively decode each subsequent element.

Perl Solution

ch-2.pl

#!/usr/bin/perl use strict; use warnings; use feature 'say'; use Test::More tests => 3; sub decode_xor { my ($encoded_ref, $initial) = @_; die "First argument must be an array reference" unless ref $encoded_ref eq 'ARRAY'; my @original = ($initial); for my $enc (@$encoded_ref) { push @original, $original[-1] ^ $enc; } return \@original; } is_deeply(decode_xor([1,2,3], 1), [1,0,2,1], "Ex1"); is_deeply(decode_xor([6,2,7,3], 4), [4,2,0,7,4], "Ex2"); is_deeply(decode_xor([], 10), [10], "Empty");

Python Solution

ch-2.py

def decode_xor(encoded: list[int], initial: int) -> list[int]: original = [initial] for enc in encoded: original.append(original[-1] ^ enc) return original