[백준] 14681 | 사분면 고르기 | 자바스크립트

문제

https://www.acmicpc.net/problem/14681

 

정답 코드

해당 문제를 기존에 사용하던 방식대로 fs 모듈을 활용해 입력을 처리했더니, Error: EACCES: permission denied 라는 런타임 오류가 발생했다. 

알고보니 문제마다 입력받는 방식에 차이가 있을 수 있나보다. 🧐 이 문제는 fs 모듈 대신 readline 모듈을 사용하거나 readFileSync(0) 을 사용해야한다.

 

readline 모듈 방식

const readline = require("readline");

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

const getQuadrant = (x, y) => {
  if (x > 0 && y > 0) {
    return 1;
  } else if (x < 0 && y > 0) {
    return 2;
  } else if (x < 0 && y < 0) {
    return 3;
  } else {
    return 4;
  }
};

const solution = (input) => {
  const [x, y] = input.map(Number);
  console.log(getQuadrant(x, y));
};

/** 입력 처리 */
let input = [];
rl.on("line", (line) => {
  input.push(line);
  if (input.length === 2) {
    solution(input);
    rl.close();
  }
});
  • readline 모듈 사용
    • readline.createInterface 를 사용하여 포준 입력(stdin)과 표준 출력(stdout)을 처리
  • 입력 처리
    • rl.on("line", callback) 으로 한 줄씩 입력 받아 배열 input 에 저장
    • 두 줄의 입력(x,y)이 모두 들어오면 solution 함수가 실행되고, rl.close() 로 입력을 종료

 

readFileSync(0) 사용

const fs = require("fs");
const filePath = process.platform === "linux" ? "/dev/stdin" : "./input.txt";

const input = fs
  .readFileSync(0)
  .toString()
  .trim()
  .split("\n")
  .map(Number);

const getQuadrant = (x, y) => {
  if (x > 0 && y > 0) {
    return 1;
  } else if (x < 0 && y > 0) {
    return 2;
  } else if (x < 0 && y < 0) {
    return 3;
  } else {
    return 4;
  }
};

function solution(input) {
  const [x, y] = input;
  return getQuadrant(x, y);
}

console.log(solution(input));