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?

【配列 1】平面で計算

Posted at

今回は paiza の「【配列 1】平面で計算」の問題に挑戦!


問題概要

〇 入力
N × N の二次元配列が与えられる(1 ≤ N ≤ 100)

〇 処理
次の「列の和」をすべて求める

  • 各横列(行ごとの合計)
  • 各縦列(列ごとの合計)
  • 左上から右下への斜め(対角線)
  • 右上から左下への斜め(逆対角線)

〇 出力

  • それらの和の中で最大の値



入力例:

3
1 2 3
4 5 6
7 8 9

出力例:

24






✅OK例:

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

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

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

    const row = []; // 各行の和
    const col = []; // 各列の和
    let diag1 = 0;   // 左上→右下の対角線
    let diag2 = 0;   // 右上→左下の対角線

    for (let i = 0; i < N; i++) {
        let tempRow = 0;
        let tempCol = 0;

        for (let j = 0; j < N; j++) {
            tempRow += grid[i][j];  // 行の和
            tempCol += grid[j][i];  // 列の和
        }
        row.push(tempRow);
        col.push(tempCol);

        diag1 += grid[i][i];           // 主対角線
        diag2 += grid[i][N - 1 - i];   // 逆対角線
    }

    // 最大値を求める
    const ans = Math.max(...row, ...col, diag1, diag2);
    console.log(ans);
});
  • 行の和 → grid[i][j]j で回して合計
  • 列の和 → grid[j][i]j で回して合計
  • 斜めの和
    • 主対角線:grid[i][i]
    • 逆対角線:grid[i][N - 1 - i]
  • 配列の最大値 → Math.max(...配列)






📝まとめ

  • 二次元配列の入力処理
    lines.slice(1).map(line => line.split(' ').map(Number)) で入力を数値の二次元配列に変換できる。

  • 縦・横の和を求める方法
    → 二重ループで row(横列)と col(縦列)を同時に計算できる。

  • 斜めの和を求める方法
    • 左上から右下の斜め: grid[i][i]
    • 右上から左下の斜め: grid[i][N - 1 - i]

  • 最大値の求め方
    → それぞれの和を計算してから Math.max(...row, ...col, diag1, diag2) で一番大きいものを出す。




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

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?