Post

백준 자바스크립트(Node.js) 입출력 정리

백준 자바스크립트(Node.js) 입출력 정리

0. 들어가기 전


백준에서 자바스크립트(Node.js)로 문제를 풀려면 먼저 입출력 처리 방식을 이해해야 한다. 파이썬이나 자바와 달리, 자바스크립트는 온라인 저지 환경에서 기본적인 입력 함수(input(), Scanner)가 없기 때문에 직접 표준 입력을 읽어와야 한다. 따라서 fs.readFileSync 또는 readline을 이용해 데이터를 읽고, 상황에 맞게 공백이나 개행 단위로 파싱하는 방법을 익혀야 문제 풀이에 집중할 수 있다.

1. 입출력 방식


백준에서 자바스크립트(Node.js)로 문제를 풀 때 사용할 수 있는 입력 처리 방식은 크게 두 가지가 있다.

  1. fs (File System) 방식
  2. readline 방식

1-1. 백준에서 권장하는 방식


백준 공식 예제 코드(예: 1000번 A+B)는 기본적으로 fs.readFileSync('/dev/stdin') 방식을 사용한다. 이는 리눅스 환경에서 표준 입력을 바로 읽는 가장 단순하고 빠른 방법이다. 따라서 대부분의 경우에는 fs 방식을 사용하는 것이 권장된다.

1-2. fsreadline 차이점


구분fs 방식readline 방식
입력 처리한 번에 전체 입력을 읽음 (배치)한 줄씩 읽음 (스트리밍)
코드 길이짧고 간단길고 보일러플레이트 많음
성능빠르고 안정적큰 입력에서 메모리 절약 가능
사용 편의공백/개행을 한 번에 파싱하기 좋음줄 단위로 처리해야 할 때 유리
권장도⭐⭐⭐⭐⭐ (기본 선택)⭐⭐☆☆☆ (특수 케이스)

2. 백준에서 fs 방식 사용법


2-1. 입력 값이 하나 일 경우 (문자)


1
2
3
4
5
6
// input : Hello
// output : Hello

const input = require("fs").readFileSync("/dev/stdin").toString().trim();

console.log(input);

2-2. 입력 값이 하나 일 경우 (숫자)


1
2
3
4
5
6
7
8
// input : 111
// output : 111

const input = require("fs").readFileSync("/dev/stdin").toString().trim();

let num = parseInt(input)

console.log(num);

2-3. 입력 값이 한 줄로 띄어쓰기 되어 구분될 경우 (문자)


1
2
3
4
5
6
7
8
9
10
11
12
// input : Hello World
// output : 
// Hello
// World

const input = require("fs").readFileSync("/dev/stdin").toString().trim().split(" ");

let s1 = input[0];
let s2 = input[1];

console.log(s1);
console.log(s2);

2-4. 입력 값이 한 줄로 띄어쓰기 되어 구분될 경우 (숫자)


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
// input : 4 16
// output : 
// 4
// 16

const input = require("fs")
  .readFileSync("/dev/stdin")
  .toString()
  .trim()
  .split(" ")
  .map(Number);

let n1 = input[0];
let n2 = input[1];

console.log(n1);
console.log(n2);

2-5. 입력 값이 여러 줄로 구분될 경우 (문자)


1
2
3
4
5
6
7
8
9
10
11
12
13
14
// input : 
// Hello 
// World
// output : 
// Hello
// World

const input = require("fs").readFileSync("/dev/stdin").toString().trim().split("\n");

let s1 = input[0];
let s2 = input[1];

console.log(s1);
console.log(s2);

2-6. 입력 값이 여러 줄로 구분될 경우 (숫자)


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
// input : 
// 4
// 16
// output : 
// 4
// 16

const input = require("fs")
  .readFileSync("/dev/stdin")
  .toString()
  .trim()
  .split("\n")
  .map(Number);

let n1 = input[0];
let n2 = input[1];

console.log(n1);
console.log(n2);

2-7. 입력 값이 여러 줄의 값들로 줄마다 띄어쓰기 되어 구분될 경우 (문자)


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
// input :
// ab cd
// ef gh
// output :
// ab cd
// ef gh

const input = require("fs")
  .readFileSync("/dev/stdin")
  .toString()
  .trim()
  .split("\n");

let [s1, s2] = input[0].split(" ");
let [s3, s4] = input[1].split(" ");

console.log(s1, s2);
console.log(s3, s4);

2-8. 입력 값이 여러 줄의 값들로 줄마다 띄어쓰기 되어 구분될 경우 (숫자)


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
// input :
// 1 2
// 3 4
// output :
// 1 2
// 3 4

const input = require("fs")
  .readFileSync("/dev/stdin")
  .toString()
  .trim()
  .split("\n");

let [n1, n2] = input[0].split(" ").map(Number);
let [n3, n4] = input[1].split(" ").map(Number);

console.log(n1, n2);
console.log(n3, n4);

3. 백준에서 readline 방식 사용법


readline은 표준 입력을 줄 단위로 처리할 때 사용하는 방식이다. 특히 입력의 크기가 크거나, 실시간 스트리밍처럼 한 줄씩 처리할 필요가 있을 때 적합하다.

백준에서는 fs 방식이 더 간단하고 권장되지만, readline은 다음과 같은 경우 유용하다:

  • 입력이 매우 많아서 한 번에 다 읽기 부담스러운 경우
  • 한 줄씩 즉시 처리해야 하는 경우

3-1. 기본 구조


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
const readline = require("readline");

const rl = readline.createInterface({
  input: process.stdin,
  output: process.stdout,
});

let input = [];

rl.on("line", function (line) {
  input.push(line); // 입력 줄을 배열에 저장
}).on("close", function () {
  // 모든 입력이 끝났을 때 실행
  console.log(input);
  process.exit();
});

3-2. 입력 값이 하나 일 경우 (문자)


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
// input : Hello
// output : Hello

const readline = require("readline");

const rl = readline.createInterface({
  input: process.stdin,
  output: process.stdout,
});

let input = "";

rl.on("line", function (line) {
  input = line;
}).on("close", function () {
  console.log(input);
  process.exit();
});

3-3. 입력 값이 하나 일 경우 (숫자)


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
// input : 111
// output : 111

const readline = require("readline");

const rl = readline.createInterface({
  input: process.stdin,
  output: process.stdout,
});

let num = 0;

rl.on("line", function (line) {
  num = parseInt(line);
}).on("close", function () {
  console.log(num);
  process.exit();
});

3-4. 입력 값이 한 줄로 띄어쓰기 되어 구분될 경우 (문자)


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
// input : Hello World
// output : 
// Hello
// World

const readline = require("readline");

const rl = readline.createInterface({
  input: process.stdin,
  output: process.stdout,
});

let input = [];

rl.on("line", function (line) {
  input = line.split(" ");
}).on("close", function () {
  let s1 = input[0];
  let s2 = input[1];
  console.log(s1);
  console.log(s2);
  process.exit();
});

3-5. 입력 값이 한 줄로 띄어쓰기 되어 구분될 경우 (숫자)


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
// input : 4 16
// output : 
// 4
// 16

const readline = require("readline");

const rl = readline.createInterface({
  input: process.stdin,
  output: process.stdout,
});

let input = [];

rl.on("line", function (line) {
  input = line.split(" ").map(Number);
}).on("close", function () {
  let n1 = input[0];
  let n2 = input[1];
  console.log(n1);
  console.log(n2);
  process.exit();
});

3-6. 입력 값이 여러 줄로 구분될 경우 (문자)


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
// input : 
// Hello
// World
// output : 
// Hello
// World

const readline = require("readline");

const rl = readline.createInterface({
  input: process.stdin,
  output: process.stdout,
});

let input = [];

rl.on("line", function (line) {
  input.push(line);
}).on("close", function () {
  let s1 = input[0];
  let s2 = input[1];
  console.log(s1);
  console.log(s2);
  process.exit();
});

3-7. 입력 값이 여러 줄로 구분될 경우 (숫자)


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
// input : 
// 4
// 16
// output : 
// 4
// 16

const readline = require("readline");

const rl = readline.createInterface({
  input: process.stdin,
  output: process.stdout,
});

let input = [];

rl.on("line", function (line) {
  input.push(parseInt(line));
}).on("close", function () {
  let n1 = input[0];
  let n2 = input[1];
  console.log(n1);
  console.log(n2);
  process.exit();
});

3-8. 입력 값이 여러 줄의 값들로 줄마다 띄어쓰기 되어 구분될 경우 (문자)


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
// input :
// ab cd
// ef gh
// output :
// ab cd
// ef gh

const readline = require("readline");

const rl = readline.createInterface({
  input: process.stdin,
  output: process.stdout,
});

let input = [];

rl.on("line", function (line) {
  input.push(line.split(" "));
}).on("close", function () {
  let [s1, s2] = input[0];
  let [s3, s4] = input[1];
  console.log(s1, s2);
  console.log(s3, s4);
  process.exit();
});

3-9. 입력 값이 여러 줄의 값들로 줄마다 띄어쓰기 되어 구분될 경우 (숫자)


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
// input :
// 1 2
// 3 4
// output :
// 1 2
// 3 4

const readline = require("readline");

const rl = readline.createInterface({
  input: process.stdin,
  output: process.stdout,
});

let input = [];

rl.on("line", function (line) {
  input.push(line.split(" ").map(Number));
}).on("close", function () {
  let [n1, n2] = input[0];
  let [n3, n4] = input[1];
  console.log(n1, n2);
  console.log(n3, n4);
  process.exit();
});
This post is licensed under CC BY 4.0 by the author.