每周挑战:新年,新挑战

发布: (2026年1月2日 GMT+8 13:39)
3 min read
原文: Dev.to

Source: Dev.to

新年快乐,大家!

每周,Mohammad S. Anwar 会发布 The Weekly Challenge,这是我们一起为两个每周任务编写解法的机会。我的解答首先用 Python 编写,然后转换为 Perl。这是我们练习编程的绝佳方式。

任务 1:最小绝对差

任务

给定一个由互不相同的整数构成的数组。

编写脚本,找出所有具有最小绝对差的元素对。

* `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`.

任务 2:矩阵平移

任务

编写脚本,将给定矩阵平移 k 次。

我的解决方案

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 )
      . ',)';
}

示例

$ ./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],)
Back to Blog

相关文章

阅读更多 »

66. 加一

问题描述:给定一个用整数数组 digits 表示的大整数,其中每个 digits[i] 是该整数的第 i 位数字。数字是或……