LoginSignup
0
0

More than 3 years have passed since last update.

Perl で二次元配列の行と列を入れ替える

Last updated at Posted at 2021-02-03

Perl を書いていて二次元配列の行と列を入れ替える関数が欲しくなったため作成してみました。

関数

sub transpose {
    my @dimension_array = @_;

    my @result;
    my @first_row = @{$dimension_array[0]};
    foreach my $column_index (0..$#first_row) {
        my @row;
        foreach my $row_index (0..$#dimension_array) {
            push @row, @{$dimension_array[$row_index]}[$column_index];
        }

        push @result, \@row;
    }

    return @result;
}

使用例

my @row1 = (1, 2, 3);
my @row2 = (4, 5, 6);
my @row3 = (7, 8, 9);
my @array = (\@row1, \@row2, \@row3);

foreach my $row (@array) {
    print "@{$row}\n";
}
# => 1 2 3
#    4 5 6
#    7 8 9

my @transposed_array = transpose(@array);
foreach my $row (@transposed_array) {
    print "@{$row}\n";
}
# => 1 4 7
#    2 5 8
#    3 6 9

0
0
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0