Languages/JavaScript

[TIL] 자바스크립트(node.js)로 백준을 풀어보자

성중 2023. 1. 30. 15:02

 

초보자가 자바스크립트로 백준 문제 푸는 법 🤔

스터디에서 백준 문제를 도전하게 되어 위 영상을 참고해 node.js 입력 방법을 정리해 보았다

 


예시로 백준 4344번 문제를 풀어보겠다🔽

 

4344번: 평균은 넘겠지

대학생 새내기들의 90%는 자신이 반에서 평균은 넘는다고 생각한다. 당신은 그들에게 슬픈 진실을 알려줘야 한다.

www.acmicpc.net

 

1단계

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
  • js 파일과 동일 경로에 문제 입력을 담은 txt 파일 생성

 

2단계 (거의 고정)

const fs = require("fs");
const filePath =
  process.platform === "linux" ? "/dev/stdin" : __dirname + "/input.txt";
const input = fs.readFileSync(filePath).toString().trim().split("\n");

console.log(input);
  • fs(File System) 모듈을 사용해 readFileSync 메소드로 입력 값 읽기
  • 백준 사이트와 같은 linux 환경 경로와 VS Code 환경 경로 따로 관리
  • split 메소드로 한 줄씩 자를 때 \r이 붙을 수 있는데 무시해도 됨

 

3단계

const fs = require("fs");
const filePath =
  process.platform === "linux" ? "/dev/stdin" : __dirname + "/input.txt";
const input = fs.readFileSync(filePath).toString().trim().split("\n");

const inputCount = Number(input[0]);
const testCases = [];

for (let i = 1; i <= inputCount; i++) {
  const temp = input[i].split(" ").map(Number);
  const testCase = {
    N: temp[0],
    scores: temp.slice(1),
  };

  testCases.push(testCase);
}

console.log(testCases);
  • 문자열로 변환된 입력 값을 요구 사항에 맞게 테스트케이스로 가공
  • 파라미터로 활용하기 위해 배열 안의 객체 형태로 정리해주면 좋음

 

4단계

const fs = require("fs");
const filePath =
  process.platform === "linux" ? "/dev/stdin" : __dirname + "/input.txt";
const input = fs.readFileSync(filePath).toString().trim().split("\n");

const inputCount = Number(input[0]);
const testCases = [];

for (let i = 1; i <= inputCount; i++) {
  const temp = input[i].split(" ").map(Number);
  const testCase = {
    N: temp[0],
    scores: temp.slice(1),
  };

  testCases.push(testCase);
}

const solution = ({ N, scores }) => {
  /**
   * 문제 풀이
   */

  console.log("답");
};

testCases.forEach((testCase) => solution(testCase));
  • 모든 테스트케이스를 순회해 solution 함수에서 답을 콘솔로 출력하도록 가공
  • 프로그래머스/리트코드는 여기서부터 시작
const solution = ({ N, scores }) => {
  const average = scores.reduce((acc, cur) => acc + cur, 0) / N;
  const count = scores.reduce(
    (count, score) => (score > average ? count + 1 : count),
    0
  );

  console.log(`${((count / N) * 100).toFixed(3)}%`);
};

WOW ~ 이제 풀어주면 된다 🤓

 


백준에서 node.js로 문제를 풀면 종종 맞아도 통과하지 못하는 경우와 마주칠 수 있다 (맞왜틀?)

이는 시간 제한메모리 제한 때문이니, node.js로 풀 수 있는 문제인지 미리 체크하도록 하자 !

 

Reference🔽

 

[백준-node.js] JavaScript 입력 - vsCode에서 풀기

코딩 테스트 연습할 때 프로그래머스를 주로 사용하여 연습하였다. 프로그래머스를 사용한 제일 큰 이유는 입력이 함수의 매개변수로 들어와서 문제 풀기가 쉽기 때문이다. 하지만 백준싸이트

wonyoung2257.tistory.com

 

자바스크립트 백준 입력받는법 및 error: ENOENT: no such file or directory, open './input.txt' 에러 해결 과정

자바스크립트로 백준 풀려면 입력 받는것 때문에 꽤나 귀찮고 나같은 초보자들은 처음에는 매우 힘들것이다. 백준에서 node.js 를 선택하고 코드 몇줄을 입력을 해야한다. const fs = require('fs'); //

broadway.tistory.com

 

GitHub - haesoo-y/baekjoon-for-js: 👊 자바스크립트로 백준 알고리즘 문제를 풀어보자

👊 자바스크립트로 백준 알고리즘 문제를 풀어보자. Contribute to haesoo-y/baekjoon-for-js development by creating an account on GitHub.

github.com