Weekly Challenge: New Year, New Challenges
Source: Dev.to
Happy New Years everyone.
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: Min Abs Diff
Task
You are given an array of distinct integers.
Write a script to find all pairs of elements with the minimum absolute difference.
* `a`, `b` are from the given array.
* `a list:
ints = sorted(ints)
min_abs_diff = None
result = []
for i in range(len(ints) - 1):
abs_diff = ints[i + 1] - ints[i]
if min_abs_diff is None or abs_diff 0`.
Task 2: Shift Matrix
Task
Write a script to shift the given matrix k times.
My solution
Python
def shift_grid(matrix: list[list[int]], k: int) -> list[list[int]]:
row_length = len(matrix[0])
for row in matrix:
if len(row) != row_length:
raise ValueError("All rows must have the same length")
flattened_list = [num for row in matrix for num in row]
k = k % len(flattened_list)
rotated_list = flattened_list[-k:] + flattened_list[:-k]
new_matrix = []
for i in range(0, len(rotated_list), row_length):
new_matrix.append(rotated_list[i:i + row_length])
return new_matrix
Perl
sub main ( $matrix_json, $k ) {
my $matrix = decode_json($matrix_json);
my $row_length = scalar( @{ $matrix->[0] } );
foreach my $row (@$matrix) {
if ( scalar(@$row) != $row_length ) {
die "All rows must have the same length\n";
}
}
my @flattened_list = map { @$_ } @$matrix;
$k = $k % scalar(@flattened_list);
splice( @flattened_list, 0, 0, splice( @flattened_list, -$k ) );
my @new_matrix = ();
for ( my $i = 0 ; $i <= $#flattened_list ; $i += $row_length ) {
push @new_matrix, [ @flattened_list[ $i .. $i + $row_length - 1 ] ];
}
say '('
. join( ",\n ",
map { '[' . join( ', ', @$_ ) . ']' } @new_matrix )
. ',)';
}
Examples
$ ./ch-2.py "[[1, 2, 3], [4, 5, 6], [7, 8, 9]]" 1
([9, 1, 2],
[3, 4, 5],
[6, 7, 8],)
$ ./ch-2.py "[[10, 20], [30, 40]]" 1
([40, 10],
[20, 30],)
$ ./ch-2.py "[[1, 2], [3, 4], [5, 6]]" 1
([6, 1],
[2, 3],
[4, 5],)
$ ./ch-2.py "[[1, 2, 3], [4, 5, 6]]" 5
([2, 3, 4],
[5, 6, 1],)
$ ./ch-2.py "[[1, 2, 3, 4]]" 1
([4, 1, 2, 3],)