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)]