[알고리즘] 구름 코테에서 자바스크립트로 입출력 처리하기

Jaino Song·2024년 6월 11일

알고리즘

목록 보기
3/7

입출력 처리

나는 프로그래머스가 좋아요
구름에선 백준과 같이 입출력을 따로 처리해줘야 한다. 백준에선 fs를 사용했는데, 구름에선 readline을 사용한다. 문제마다 베이스 코드가 두가지가 나온다. 아니 네이버 부스트캠프 왜 갑분 구름에서 시험 치는데;

베이스 코드 1

// Run by Node.js
const readline = require('readline');

(async () => {
	let rl = readline.createInterface({ input: process.stdin });
	
	for await (const line of rl) {
		console.log('Hello Goorm! Your input is', line);
		rl.close();
	}
	
	process.exit();
})();

베이스 코드 2

// Run by Node.js

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

rl.on("line", function(line) {
	rl.close();
}).on("close", function() {
	process.exit();
});

프로그래머스만 쓰던 나는 처음 구름에서 입출력을 따로 처리해줘야 하는 것을 보고 현기증이 날뻔 했지만, 전지전능한 chatGPT의 설명을 찬찬히 읽고 나니 그렇게 복잡한게 아니란걸 깨달았다.

입력을 받을 때의 포인트는 입력 정보를 배열에 넣으면 된다는 것이다.

입력:
4
4 5 6 7
1 2 3 4

이러한 입력을 처리해야 한다면,

베이스 코드 1

// Run by Node.js
const readline = require('readline');

(async () => {
	let rl = readline.createInterface({ input: process.stdin });
	let input = [];
	for await (const line of rl) {
		input.push(line.split(' ').map(Number));
		rl.close();
	}
	console.log(input)
    
	process.exit();
})();

베이스 코드 2

// Run by Node.js

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));
	rl.close();
}).on("close", function() {
	console.log(input)
	process.exit();
});

이렇게 입력을 input 배열에 넣은 후에 필요에 따라 꺼내 쓰면 된다. 출력도 rl.close(), 그러니까 readline이 입력을 받는 것을 끝낸 후에 로직을 짠 후에 정답을 출력해주면 된다.

profile
하루하루 목표를 향해 나아가야지

0개의 댓글