2차원 배열


2738번 (행렬 덧셈)

const fs = require("fs");
const input = fs.readFileSync("./input.txt").toString().trim().split("\n");
const [N, M] = input[0].split(' ').map(Number);
let matrixA = [];
let matrixB = [];
let answer = ' ';
for (let i = 1; i <= N; i++) {
matrixA.push(input[i].split(' ').map(Number));
}
for (let i = N+1; i <= 2*N; i++) {
matrixB.push(input[i].split(' ').map(Number));
}
for (let i = 0; i < N; i++) {
for (let j = 0; j < M; j++) {
answer += String(matrixA[i][j]+matrixB[i][j]) + ' ';
}
answer += '\n';
}
console.log(answer.trim());
  • 행렬 덧셈 문제이다.
  • matrixA와 matrixB를 선언하여 for문으로 해당 배열에 이중배열 형태로 행렬을 push해 주었다.
  • 2중 for문을 이용해 각 위치 숫자끼리 더해주었다.
  • trim()으로 정리 후 출력했다.
  • 2566번 (최댓값)

    const fs = require("fs");
    const input = fs.readFileSync("./input.txt").toString().trim().split('\n');
    let arr = [];
    let max = 0;
    let locationMax = '';
    for (let i = 0; i < 9; i++) {
    arr.push(input[i].split(" ").map(Number));
    }
    for (let i = 0; i < 9; i++) {
    for (let j = 0; j < 9; j++) {
    if (max <= arr[i][j]) {
    max = arr[i][j];
    locationMax = (i+1) + ' ' + (j+1);
    }
    }
    }
    console.log(max);
    console.log(locationMax);
  • input을 한 줄씩 잘라 받는다.
  • 또 다시 input의 인덱스 별로 띄어쓰기를 기준으로 잘라 arr에 push 한다.
  • 2중 for문으로 모든 요소를 돌면서, max에 가장 큰 값을 기록한다. locationMax에는 그 위치를 기록한다.
  • max와 locationMax를 출력한다.
  • 2563번 (색종이)

    const fs = require("fs");
    const input = fs.readFileSync("./input.txt").toString().trim().split('\n');
    const paperNum = parseInt(input[0]);
    let colorPaperArr = [];
    let paper = [];
    let x = 0;
    let y = 0;
    let count = 0;
    input.shift();
    for (let i = 0; i < paperNum; i++) { // input값을 colorPaperArr에 정리
    colorPaperArr.push(input[i].split(' ').map(Number));
    }
    for (let i = 0; i < 100; i++) { // 도화지 생성
    let oneLine = new Array(100);
    oneLine.fill(false);
    paper.push(oneLine);
    }
    for (let i = 0; i < paperNum; i++) { // 색종이가 붙어있는 위치는 true로 변경
    x = colorPaperArr[i][0];
    y = colorPaperArr[i][1];
    for (let j = x; j < x+10; j++) {
    for (let k = y; k < y+10; k++) {
    paper[j][k] = true;
    }
    }
    }
    for (let i = 0; i < 100; i++) { // true 개수 count
    for (let j = 0; j < 100; j ++) {
    if (paper[i][j]) {
    count++;
    }
    }
    }
    console.log(count);
  • 우선 input으로 들어온 색종이가 붙은 위치를 2차원 배열로 정리한다.
  • 이후 해당 색종이를 붙일 도화지를 생성한다.
  • 도화지 배열은 100X100의 2차원 배열이며, 초기에는 모두 false 값으로 세팅한다.
  • 색종이가 붙은 위치의 배열을 돌면서 x축 값과 y축 값을 입력받아 색종이의 한 변의 길이가 10임을 고려하여 해당 위치를 모두 true로 해준다.
  • 마지막으로 true의 개수를 count 변수로 센다.
  • count를 출력한다.