문제
2738번: 행렬 덧셈
첫째 줄에 행렬의 크기 N 과 M이 주어진다. 둘째 줄부터 N개의 줄에 행렬 A의 원소 M개가 차례대로 주어진다. 이어서 N개의 줄에 행렬 B의 원소 M개가 차례대로 주어진다. N과 M은 100보다 작거나 같
www.acmicpc.net
정답
const fs = require("fs");
const filePath = process.platform === "linux" ? "/dev/stdin" : "test.txt";
const input = fs
.readFileSync(filePath)
.toString()
.split("\n")
.map(str => str.split(" ").map(Number));
// 첫 번째 행을 A, B의 행렬 크기를 알려주는 변수로 따로 빼기
const matrix = input.shift();
const row = matrix[0];
// row를 기준으로 A와 B를 분리
const A = input.slice(0, row);
const B = input.slice(row);
const answer = [];
// A와 B에서 같은 행, 열의 수를 더하기
for (let i = 0; i < A.length; i++) {
let tmp = "";
for (let j = 0; j < A[i].length; j++) {
tmp += A[i][j] + B[i][j] + " ";
}
answer.push(tmp);
}
answer.forEach(item => console.log(item));