0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

転置行列って聞くと一瞬ひるむけど、実はただの「行と列の反転」!


問題概要

N 行 K 列 の2次元配列を、K 行 N 列 の 転置行列 に変換して出力せよ。


入力例:

2 3
1 2 3
4 5 6

出力例:

1 4
2 5
3 6




🟥 NG例

const rl = require('readline').createInterface({input:process.stdin});
const lines = [];

rl.on('line', (input) => {
    lines.push(input);
});


rl.on('close', () => {
    const [N, K] = lines[0].split(' ').map(Number);

    const arrA = lines.slice(1).map(line => line.split(' '));
    
    for(let i = 0; i < N; i++){
        const row = [];
        
        for(let j = 0; j < K; j++){
            row.push(arrA[i][j]);
        }
        
        console.log(row.join(' '));
    }
    
});

👉 これだとただの出力。行と列の立場逆転をしないと転置にはならない!



🟩 OK例①:for文で正攻法

for(let i = 0; i < K; i++){
    const row = [];
    for(let j = 0; j < N; j++){
        row.push(arrA[j][i]);
    }
    console.log(row.join(' '));
}

✅ 解説:外ループが元の列番号=転置後の行、内ループが元の行=転置後の列。



🟨 OK例②:Array.from

const transposed = Array.from({ length: K }, (_, i) =>
  Array.from({ length: N }, (_, j) => arrA[j][i])
);

transposed.forEach(row => console.log(row.join(' ')));

✅ 解説
Array.from({ length: K }, (_, i) => …)

  • 長さ K の配列(転置後の行数)を作る。
  • i は転置行のインデックス。

Array.from({ length: N }, (_, j) => arrA[j][i])

  • その行を構成するために、元の配列の各行から i 番目の値を集める。



🟦 OK例③:map()

const transposed = arrA[0].map((_, i) => arrA.map(row => row[i]));

transposed.forEach(row => console.log(row.join(' ')));

✅ 解説
arrA[0].map((_, i) => …)

  • 最初の行から 列数分だけループさせる。
  • i が列インデックス(転置後の行インデックス)。

arrA.map(row => row[i])

  • 各行から i 番目の要素を抜き出して、列 → 行にする。




📝メモ&学んだことまとめ

  • Array.from({ length }, (_, i) => ...) の使い方(配列初期化に便利)
  • 2次元配列の扱い方、行→列の切り替えのロジック
  • 高階関数( .map() )が2重でも思ったより読める




僕の失敗談(´;ω;`)と解決法🐈

0
0
0

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?