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?

More than 1 year has passed since last update.

paizaラーニング レベルアップ問題集 新・Bランクレベルアップメニュー JavaScript 【配列 1】平面で計算

Last updated at Posted at 2023-02-26

【配列 1】平面で計算 (paizaランク C 相当)

解答例(C++の場合参考)

縦横斜めそれぞれ和を求め、最大値比較する。

const fs = require("fs");
const input = fs.readFileSync("/dev/stdin", "utf-8").trim();
const lines = input.split("\n");

const N = Number(lines[0]);
const A = lines.slice(1).map(line => line.split(" ").map(Number));

let ans = 0;
//縦横
for (let i = 0; i < N; i++) {
  let row_sum = 0;//横行
  let col_sum = 0;//縦列
  for (let j = 0; j < N; j++) {
    row_sum += A[i][j];
    col_sum += A[j][i];
  }
  ans = Math.max(row_sum, col_sum, ans);
}
  
//斜め
let left_right_down = 0;//右下へ
let left_right_up = 0;//右上へ

for (let i = 0; i < N; i++) {
  left_right_down += A[i][i];
  left_right_up += A[N - 1 - i][i];
}
ans = Math.max(left_right_down, left_right_up, ans);

console.log(ans);

応用例

全ての斜めの和についても実装してみた。

const fs = require("fs");
const input = fs.readFileSync("/dev/stdin", "utf-8").trim();
const lines = input.split("\n");

const N = Number(lines[0]);
const A = lines.slice(1).map(line => line.split(" ").map(Number));

let max = 0;
//縦列
for (let j = 0; j < N; j++) { //列固定
  let sum = 0;
  for (let i = 0; i < N; i++) { //行、縦に足してく
    sum += A[i][j];
  }
  max = Math.max(max, sum);
}

//横列
max = A.reduce((acc, row) => Math.max(acc, row.reduce((a, b) => a + b)), max);

//斜め列
//右上に
//スタート地点、左上隅から左下へ
for (i = 0; i < N; i++) {
  //右上に足してく
  let sum = 0;
  for (let a = 0; a <= i; a++) { //右上へ
    sum += A[i - a][a];
  }
  max = Math.max(max, sum);
}

//スタート地点、左下から右下へ
for (let j = 1; j < N; j++) {
  //右上に足してく
  let sum = 0;
  for (let a = 0; a < N - j; a++) { //右上へ
    sum += A[N - 1 - a][j + a];
  }
  max = Math.max(max, sum);
}

//右下に
//スタート地点、左上から右上へ
for (j = 0; j < N; j++) {
  //右下に足してく
  let sum = 0;
  for (let a = 0; a < N - j; a++) { //右下へ
    sum += A[a][j + a];
  }
  max = Math.max(max, sum);
}

//スタート地点、左上から左下へ
for (i = 1; i < N; i++) {
  //右下に足してく
  let sum = 0;
  for (let a = 0; a < N - i; a++) { //右下へ
    sum += A[i + a][a];
  }
  max = Math.max(max, sum);
}
console.log(max);
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?