The Weekly Challenge 324

Array Reshaping & Subset XOR Sums!

Original Challenge Link | Solutions on GitHub

Task 1: 2D Array

"The Reshaper: Flattened Lists to Matrix View!"

Given a flat array of integers and dimensions r (rows) and c (columns), reshape the array into an r x c matrix filled row-wise.

The Strategy: Iterate through the target number of rows. For each row at index i, extract a slice from the original array starting at i * c and ending at (i + 1) * c. In Python, this is elegantly handled by list slicing. In Perl, we can use array slices @ints[start .. end].
Perl Implementation
sub make_2d_array {
    my ($r, $c, @ints) = @_;
    my @rows;
    for my $i (0 .. $r - 1) {
        my $start = $i * $c;
        push @rows, [ @ints[ $start .. $start + $c - 1 ] ];
    }
    return \@rows;
}
Python Implementation
def make_2d_array(r: int, c: int, ints: list[int]) -> list[list[int]]:
    return [ints[i * c : (i + 1) * c] for i in range(r)]

Task 2: Total XOR

"Bitwise Bounty: Summing XOR Results of All Subsets!"

Calculate the XOR sum of every non-empty subset of an input array and return the total sum of these results.

The Strategy: Use a bitmask to iterate through all ^n - 1$ non-empty subsets. For each mask, the bits set to 1 indicate which elements of the original array are included in the subset. XOR these elements together to find the subset's XOR value, then add that value to a running total. For very large arrays, a bit-counting optimization exists, but for these examples, the brute-force subset generation is sufficient.
Perl Implementation
sub total_xor {
    my (@ints) = @_;
    my $sum = 0;
    my $n   = scalar @ints;
    my $subsets = 1 << $n;
    for my $mask (1 .. $subsets - 1) {
        my $xor = 0;
        for my $i (0 .. $n - 1) {
            $xor ^= $ints[$i] if $mask & (1 << $i);
        }
        $sum += $xor;
    }
    return $sum;
}
Python Implementation
def total_xor(ints: list[int]) -> int:
    n = len(ints)
    total = 0
    for mask in range(1, 1 << n):
        xor_val = 0
        for i in range(n):
            if mask & (1 << i):
                xor_val ^= ints[i]
        total += xor_val
    return total