✨JSY
article thumbnail
Published 2023. 9. 12. 11:05
백준 10813 javascript | node.js PS/백준
문제

문제 출처 - https://www.acmicpc.net/problem/10813

 

10813번: 공 바꾸기

도현이는 바구니를 총 N개 가지고 있고, 각각의 바구니에는 1번부터 N번까지 번호가 매겨져 있다. 바구니에는 공이 1개씩 들어있고, 처음에는 바구니에 적혀있는 번호와 같은 번호가 적힌 공이

www.acmicpc.net

풀이

fill과 map 메소드를 이용하여 1 2 ... N 까지 넣은 array를 생성한다.

let arr = new Array(N)				// N개의 빈 공간 생성
		 .fill(1)			// 모두 1을 넣음
		 .map((a, b) => a + b);		// 1, 1+1, 1+1+1, 1+1+1+1, ...

 

그 다음

tmp라는 변수 활용하여 수 바꾸기

tmp = arr[a - 1]; // 정수 X를 tmp에 저장
arr[a - 1] = arr[b - 1]; // 정수 X를 정수 Y를 넣음
arr[b - 1] = tmp; // 정수 Y에 tmp 값을 넣음

 

코드
const fs = require('fs');
const filePath = process.platform === 'linux' ? '/dev/stdin' : './input.txt';
let input = fs.readFileSync(filePath).toString().split('\n');

const [N, M] = input[0].split(' ').map((item) => +item);

let arr = new Array(N).fill(1).map((a, b) => a + b);

for (let i = 1; i <= M; i++)
{
    let tmp = 0;
    let [a, b] = input[i].split(' ').map((item) => +item);

    tmp = arr[a - 1];
    arr[a - 1] = arr[b - 1];
    arr[b - 1] = tmp;
}

console.log(arr.join(' '));

'PS > 백준' 카테고리의 다른 글

백준 3052 javascript | node.js  (0) 2023.09.12
백준 5597 javascript | node.js  (0) 2023.09.12
백준 10810 javascript | node.js  (0) 2023.09.12
백준 10807 javascript | node.js  (0) 2023.09.12
백준 15552 javascript | node.js  (0) 2023.08.30
profile

✨JSY

@JUNSANG YOO

포스팅이 좋았다면 "좋아요❤️" 또는 "구독👍🏻" 해주세요!