❓Problem
🥉🖐️
N*M크기의 두 행렬 A와 B가 주어졌을 때,
두 행렬을 더하는 프로그램을 작성하시오.
🔑Input
첫째 줄에 행렬의 크기 N 과 M이 주어진다.
둘째 줄부터 N개의 줄에 행렬 A의 원소 M개가 차례대로 주어진다.
이어서 N개의 줄에 행렬 B의 원소 M개가 차례대로 주어진다.
N과 M은 100보다 작거나 같고, 행렬의 원소는 절댓값이 100보다 작거나 같은 정수이다.
3 3
1 1 1
2 2 2
0 1 0
3 3 3
4 4 4
5 5 100
🔒Output
첫째 줄부터 N개의 줄에 행렬 A와 B를 더한 행렬을 출력한다.
행렬의 각 원소는 공백으로 구분한다.
4 4 4
6 6 6
5 6 100
❗Solution
const fs = require('fs');
const filePath = process.platform === 'linux' ? '/dev/stdin' : './input.txt';
let input = fs.readFileSync(filePath)
.toString()
.trim()
.split('\n')
.map(item => item.split(" ").map(Number));
// [
[ 3, 3 ],
[ 1, 1, 1 ],
[ 2, 2, 2 ],
[ 0, 1, 0 ],
[ 3, 3, 3 ],
[ 4, 4, 4 ],
[ 5, 5, 100 ]
]
const [ N, M ] = input.shift() // [ 3, 3 ]
let arr = new Array(N).fill().map(() => new Array(M).fill(0));
// [ [ 0, 0, 0 ], [ 0, 0, 0 ], [ 0, 0, 0 ] ]
for ( let i = 0; i < N; i++ ) {
for ( let j = 0; j < M; j++ ) {
arr[i][j] = input[i][j] + input[i+N][j]
}
}
// [ [ 4, 0, 0 ], [ 0, 0, 0 ], [ 0, 0, 0 ] ]
[ [ 4, 4, 0 ], [ 0, 0, 0 ], [ 0, 0, 0 ] ]
[ [ 4, 4, 4 ], [ 0, 0, 0 ], [ 0, 0, 0 ] ]
[ [ 4, 4, 4 ], [ 6, 0, 0 ], [ 0, 0, 0 ] ]
[ [ 4, 4, 4 ], [ 6, 6, 0 ], [ 0, 0, 0 ] ]
[ [ 4, 4, 4 ], [ 6, 6, 6 ], [ 0, 0, 0 ] ]
[ [ 4, 4, 4 ], [ 6, 6, 6 ], [ [ [ 4, 4, 4 ], [ 6, 6, 6 ], [ 5, 6, 100 ] ]
// [ [ 4, 4, 4 ], [ 6, 6, 6 ], [ 5, 6, 100 ] ]
// 출력 값을 맞춰주기 위해
// answer에 arr의 원소들을 추가해준다
let answer = "";
for ( let i = 0; i < arr.length; i++ ) {
for ( let j = 0; j < arr[0].length; j++ ) { // arr[0] [ 4, 4, 4 ]
answer += arr[i][j]+ " "
}
answer += "\n"
}
console.log(answer.trim()) // 앞뒤 공백 없애줌
// 4 4 4
6 6 6
5 6 100
💯Study
Array.prototype.fill()
Array 인스턴스의 fill() 메서드는 배열의 인덱스 범위 내에 있는 모든 요소를 정적 값으로 변경합니다.
그리고 수정된 배열을 반환합니다.
const array1 = [1, 2, 3, 4];
// Fill with 0 from position 2 until position 4
console.log(array1.fill(0, 2, 4));
// Expected output: Array [1, 2, 0, 0]
// Fill with 5 from position 1
console.log(array1.fill(5, 1));
// Expected output: Array [1, 5, 5, 5]
console.log(array1.fill(6));
// Expected output: Array [6, 6, 6, 6]
fill(value)
fill(value, start)
fill(value, start, end)
새로운 배열 arr를 크기가 N을 undefined으로 채운다.
map을 통해 arr 원소의 값에 새로운 배열 크기가 M인 0으로 채운다.
let arr = new Array(N).fill().map(() => new Array(M).fill(0));
// [ [ 0, 0, 0 ], [ 0, 0, 0 ], [ 0, 0, 0 ] ]
Reference
https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Global_Objects/Array/fill
https://www.acmicpc.net/problem/2738
'Coding Test > Baekjoon' 카테고리의 다른 글
[Baekjoon node.js] 10798번: 세로읽기 (1) | 2024.01.29 |
---|---|
[Baekjoon node.js] 2566번: 최댓값 (0) | 2024.01.25 |