본문 바로가기
JS/백준

[백준/JS] 2738. 행렬 덧셈

by GiraffePark 2023. 11. 23.

안녕하세요. 박기린 입니다.

백준 2738번 행렬 덧셈 문제를 풀어보겠습니다.

 

 


문제 링크

https://www.acmicpc.net/problem/2738

 

 

 

 

 


문제 해석

예제 입력

3 3
1 1 1
2 2 2
0 1 0
3 3 3
4 4 4
5 5 100

 

입력이 위처럼 주어집니다.

첫 번째 줄이 행렬의 크기 n과 m의 값이 적혀 있습니다. (N * M)

그 다음 줄부터는 두 개의 행렬이 적혀 있습니다.

 

 

 

위의 예제 입력을 n * m에 따라 두 개의 행렬로 나누어서 본다면, 

 

이와 같은 두 개의 2차원 배열로 구분해서 볼 수 있습니다.

 

 

 

 

이 두 행렬의 같은 위치에 있는 원소들을 합해서,

 

 

 

 

 

새로운 하나의 행렬을 만든 후 출력해주는 것이 문제의 목표입니다.

 

 

 

 


정답 코드

const fs = require("fs");
const [size, ...matrices] = fs
  .readFileSync("/dev/stdin")
  .toString()
  .trim()
  .split("\n");
let result = "";

const [n, m] = size.split(" ").map((e) => +e);
const firstMatrix = [];
const secondMatrix = [];

for (let i = 0; i < matrices.length; i++) {
  if (i < n) {
    firstMatrix.push(matrices[i].split(" ").map((e) => +e));
  } else {
    secondMatrix.push(matrices[i].split(" ").map((e) => +e));
  }
}

for (let i = 0; i < n; i++) {
  for (let j = 0; j < m; j++) {
    result += `${firstMatrix[i][j] + secondMatrix[i][j]} `;
  }
  result += "\n";
}

console.log(result);

 

 

 


정답 코드 풀이

const fs = require("fs");
const [size, ...matrices] = fs
  .readFileSync("/dev/stdin")
  .toString()
  .trim()
  .split("\n");
const [n, m] = size.split(" ").map((e) => +e);

 

fs모듈로 입력을 받은 후, n과 m이 담긴 첫 번째 줄은 size, 나머지는 matices라는 상수에 집어넣습니다.

sizesplit() 메소드와 배열 비구조화를 이용해서 nm이라는 상수에 각각 값을 담습니다.

 

 

 

const firstMatrix = [];
const secondMatrix = [];
let result = "";

첫 번째 행렬과 두 번째 행렬을 각각 담아줄 배열을 선언하고,

최종 결과를 출력할 result 변수를 만듭니다.

 

 

 

 

for (let i = 0; i < matrices.length; i++) {
  if (i < n) {
    firstMatrix.push(matrices[i].split(" ").map((e) => +e));
  } else {
    secondMatrix.push(matrices[i].split(" ").map((e) => +e));
  }
}

위 코드는, 입력받은 행렬의 인수들을 firstMatrix와 secondMatrix 배열에 각각 알맞게 담아주는 역할을 합니다.

for문의 i가 n보다 큰지 작은지를 기준으로, 어떤 배열에 담길지 결정됩니다.

 

 

 

 

for (let i = 0; i < n; i++) {
  for (let j = 0; j < m; j++) {
    result += `${firstMatrix[i][j] + secondMatrix[i][j]} `;
  }
  result += "\n";
}

n *m 으로 이루어진 firstMatrix와 secondMatrix 배열에 접근하는 이중 for문 입니다.

result가 string이므로, string의 +연산자, ${string interpolation}, '\n'을 이용해서 행렬의 합을 저장해줍니다.

 

 

 

console.log(result);

마지막으로 result를 출력하면 끝입니다.

 

 

 

 

 

반응형