✏️기록하는 즐거움
article thumbnail

Link

 

14681번: 사분면 고르기

점 (x, y)의 사분면 번호(1, 2, 3, 4 중 하나)를 출력한다.

www.acmicpc.net

문제

흔한 수학 문제 중 하나는 주어진 점이 어느 사분면에 속하는지 알아내는 것이다. 사분면은 아래 그림처럼 1부터 4까지 번호를 갖는다. "Quadrant n"은 "제n사분면"이라는 뜻이다.

예를 들어, 좌표가 (12, 5)인 점 A는 x좌표와 y좌표가 모두 양수이므로 제1사분면에 속한다. 점 B는 x좌표가 음수이고 y좌표가 양수이므로 제2사분면에 속한다.점의 좌표를 입력받아 그 점이 어느 사분면에 속하는지 알아내는 프로그램을 작성하시오. 단, x좌표와 y좌표는 모두 양수나 음수라고 가정한다.

입력 > 첫 줄에는 정수 x가 주어진다. (−1000 ≤ x ≤ 1000; x ≠ 0) 다음 줄에는 정수 y가 주어진다. (−1000 ≤ y ≤ 1000; y ≠ 0)
출력 > 점 (x, y)의 사분면 번호(1, 2, 3, 4 중 하나)를 출력한다.

 

제출

현재 백준에서 fs모듈 사용 시 런타임 에러가 발생한다.
따라서 readline을 권장하고 있으므로 readline으로 문제를 풀 것 :)

// fs모듈 사용
const fs = require("fs");
const input = (
  process.platform === "linux"
    ? fs.readFileSync("/dev/stdin").toString()
    : `12
    5`
).split("\n");

const [x, y] = input;

if (x > 0 && y > 0) {
  console.log(1);
} else if (x < 0 && y > 0) {
  console.log(2);
} else if (x < 0 && y < 0) {
  console.log(3);
} else {
  console.log(4);
}
// readline 모듈
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 () {
  const [x, y] = input;

  if (x > 0 && y > 0) {
    console.log(1);
  } else if (x < 0 && y > 0) {
    console.log(2);
  } else if (x < 0 && y < 0) {
    console.log(3);
  } else {
    console.log(4);
  }

  process.exit();
});

풀이과정

사분면은 원점(0, 0)을 기준으로 시계 반대방향으로 제1사분면, 제2사분면, 제3사분면, 제4사분면으로 나눠져있다.

  • 제1사분면 - x>0, y>0
  • 제2사분면 - x<0, y>0
  • 제3사분면 - x<0, y<0
  • 제4사분면 - x>0, y<0

x, y의 조건에 따라 사분면의 번호를 출력하면 된다.

 

개념

readline module

  • readline 모듈이란 Readable 스트림(ex. process.stdin) 에서 한 번에 한 줄씩 데이터를 읽기 위한 인터페이스를 제공한다.
  • 아래의 코드로 readline에 액세스 할 수 있다.
const readline = require('readline'); // readline import
  • nodejs 문서에서 기본적으로 보여주는 예시이다.
const readline = require('readline');
const { stdin: input, stdout: output } = require('process');

const rl = readline.createInterface({ input, output });

rl.question('What do you think of Node.js? ', (answer) => {
  // TODO: Log the answer in a database
  console.log(`Thank you for your valuable feedback: ${answer}`);

  rl.close();
});

> What do you think of Node.js?
>> beautiful!
> Thank you for your valuable feedback: beautiful!
  • 이 코드가 한 번 실행되면, 인터페이스가 입력 스트림에서 데이터가 수신되기까지 기다리기 때문에 Node.js 애플리케이션은 readline.Interface가 닫힐 때까지 종료되지 않는다.
  • 실행 단계는 1) readline 모듈을 import해서 interface 객체를 생성하고 2) process의 입출력 stream을 input과 output에 할당한다.
    3) rl.question() 메서드는 query를 output에 출력해서 보여주고, 사용자 입력이 제공될 때까지 기다린 다음
    4) 입력 받은 값을 answer에 전달하여 콜백 함수를 호출한다.

 

 

 

 


Comment

fs모듈 사용 시 런타임 에러 발생하여 readline 사용했다.

profile

✏️기록하는 즐거움

@nor_coding

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