Weekly Challenge 324
Each week Mohammad S. Anwar sends out The Weekly Challenge, a chance for all of us to come up with solutions to two weekly tasks. My solutions are written in Python first, and then converted to Perl. It's a great way for us all to practice some coding.
Task 1: 2D Array
Task
You are given an array of integers and two integers $r
and $c
.
Write a script to create two dimension array having $r
rows and $c
columns using the given array @ints
.
My solution
For input from the command line, I take $rows
and $cols
as the last two values, the rest is @ints
. In Python, this is achieved with the following line:
*ints, rows, cols = array
Using Python's list comprehension, the solution is a single line after doing some sanity checks of the inputs.
def twod_array(ints: list, rows: int, cols: int) -> list[list[int]]:
if rows < 1 or cols < 1:
raise ValueError("Rows and columns must be greater than 0.")
if rows * cols != len(ints):
raise ValueError("The product of rows and columns must equal the length of the input list.")
return [[ints[i * cols + j] for j in range(cols)] for i in range(rows)]
The Perl solution follows a more traditional approach.
sub main (@ints) {
my $cols = pop @ints;
my $rows = pop @ints;
if ($rows < 1 or $cols < 1) {
die "Rows and columns must be greater than 0.\n";
}
if (@ints != $rows * $cols) {
die "The product of rows and columns must equal the length of the input list.\n";
}
my @result = ();
foreach my $row (0 .. $rows - 1) {
my @row = ();
foreach my $col (0 .. $cols - 1) {
push @row, shift @ints;
}
push @result, \@row;
}
say "(" . join(", ", map { '[' . join(", ", @$_) . ']'} @result) . ")";
}
Examples
$ ./ch-1.py 1 2 3 4 2 2
[[1, 2], [3, 4]]
$ ./ch-1.py 1 2 3 1 3
[[1, 2, 3]]
$ ./ch-1.py 1 2 3 4 4 1
[[1], [2], [3], [4]]
Task 2: Total XOR
Task
You are given an array of integers.
Write a script to return the sum of total XOR for every subset of given array.
My solution
For this task, I have an iterator i
from 1 to the length of the list. For each iteration, I compute all possible combinations of this many items. Rather than reinventing a perfectly good wheel, I use the combinations
function from itertools in Python, and from Algorithm::Combinatorics in Perl. For each combination, I calculate the XOR of all items.
def total_xor(ints: list) -> int:
total = 0
for i in range(1, len(ints) + 1):
for combo in combinations(ints, i):
xor_value = 0
for num in combo:
xor_value ^= num
total += xor_value
return total
Examples
$ ./ch-2.py 1 3
6
$ ./ch-2.py 5 1 6
28
$ ./ch-2.py 3 4 5 6 7 8
480
Top comments (1)
re "Rows and columns must be greater than 0.", there's nothing in the problem that precludes either or both from being 0, and in fact your python and perl code both work fine with that :)
Some comments may only be visible to logged-in visitors. Sign in to view all comments.