BJ-14681-사분면 고르기

이은지·2022년 11월 23일
0

코딩테스트

목록 보기
22/76

문제

흔한 수학 문제 중 하나는 주어진 점이 어느 사분면에 속하는지 알아내는 것이다. 사분면은 아래 그림처럼 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 중 하나)를 출력한다.

풀이

//시도했던 모듈
//let fs = require('fs');
//let input = fs.readFileSync('/dev/stdin').toString().split(' ');

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 = input[0];
  const y = input[1];

  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 if (x > 0 && y < 0) {
    console.log("4");
  }
  process.exit();
});

readline 기본 형태

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

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

위 코드는 사용자로부터 한 줄의 입력만 받고 프로그램이 끝난다.
rl.close()부분이 없으면 무한으로 입력을 받으며 실시간으로 console.log를 찍는다

readline 예제 - 두 수를 공백으로 구분지어 합을 구하기

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((el) => parseInt(el));
  })
  .on('close', function () {
    console.log(input[0] + input[1]);
    process.exit();
  });
//입력 1 2
//출력 3

마무리

런타임에러가 계속 떴는데 그 이유를 몰랐다..
구글링해보니 fs모듈말고 readline모듈로 써야한다는 내용이 있었다
백준 = fs로 외워버린 내자신..
프리코스때 readline을 배웠는데 이렇게 활용하는지는 전혀 몰랐다

readline 참고 : https://wooooooak.github.io/node.js/2018/09/26/Node.js-%EC%9E%85%EB%A0%A5-%EB%B0%9B%EA%B8%B0/
런타임에러 참고 : https://hanch-dev.tistory.com/4

0개의 댓글