프로그래머스나 다른 알고리즘 사이트는 JavaScript의 input을 제공해주지만 백준은 JavaScript로
제출하는 조건이 없다. 그래서 node.js를 이용해 입출력을 관리하여 문제를 제출하여야 한다.
- node.js: JavaSript 엔진으로 빌드된 JavaScript 런타임 환경
따라서 node.js를 통한 입출력 관리 방법을 알아보자.
1. 입력이 한 줄인 경우
// 입력 예 => 3 1
const fs = require('fs');
let input = fs.readFileSync('/dev/stdin').toString(); // 문자 하나만 입력받을 경우
input = input.split(' '); // 한칸 띄어쓰기로 구분 input[0], input[1] 배열형식으로 꺼내쓰면 된다.
2. 입력이 여러 줄인 경우
/* 5
5 50 50 70 80 100
7 100 95 90 80 70 60 50
3 70 90 80
3 70 90 81
9 100 99 98 97 96 95 94 93 91 */
const fs = require('fs');
let input = fs.readFileSync('/dev/stdin').toString();
input = input.split('\n'); // 한 줄씩 데이터 분리
const testCaseNum = +input[0];
const inputTestCase = [];
for(let i=1; i <= testCaseNum; i++){
const arr = input[i].split(' ').map((item) => +item);
const newArr = []; // testCase의 arr
for (let i=1; i<=arr[0]; i++) {
newArr.push(arr[i]);
}
const testCase = {
N : arr[0],
arr: newArr,
};
inputTestCase.push(testCase);
}
- fs: fs 내장 모듈을 현재 파일에 불러온 뒤 readFileSync 메서드를 사용하여 해당 파일 내의 데이터를 문자열로 반환 받아 input 변수에 저장해준다.
- split(): 띄워쓰기나 줄바꿈과 같이 문자를 구분하여 배열을 생성할 때 사용한다.
- trim(): 문자열 양 끝의 불필요한 공백등을 제외시켜 준다.
'study > javascript' 카테고리의 다른 글
| [HTML/CSS/JS] 브라우저 렌더링 과정 (0) | 2023.09.10 |
|---|---|
| 실행 컨텍스트 (1) | 2023.09.04 |
| 논리 연산자를 이용한 단축평가 (0) | 2023.08.20 |
| 7장 정리 (0) | 2023.08.06 |
| [자바스크립트 Deep Dive] 4장 ) 변수 && 5장) 표현식과 문 (0) | 2023.07.27 |