알고리즘

[boj] 10825. 국영수 (node.js)

hello_sohui 2022. 1. 25. 19:58

요약

학생 N명의 이름과 과목별 점수가 주어질 때, 문제 조건에 따라 정렬한 후 정렬 결과를 학생의 이름만 출력하라.

내 풀이

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

let cnt = 0;
const input = () => {
  return stdin[cnt++];
};

function compare(a, b) {
  if (a[1] != b[1]) return -(a[1] - b[1]);
  if (a[2] != b[2]) return a[2] - b[2];
  if (a[3] != b[3]) return -(a[3] - b[3]);
  return a[0] > b[0] ? 1 : -1;
}

const N = input();
const students = [];
for (let i = 0; i < N; i++) {
  students[i] = input().split(" ");
}
students.sort(compare);
console.log(students.reduce((str, student) => (str += student[0] + "\n"), ""));

포인트

  1. 코드 작성
    • 자바스크립트에서의 sort 는 Array.prototype.sort()
      • sort 할 function을 직접 정의하여 넣어줄 수 있다.
      • function compare(a, b){}
      • myArray.sort(compare)
      • 매개변수로 array 값을 하나씩 받아가며 비교한다.
  2. compare(a, b) 함수의 리턴값
    • 음수이면 a가 먼저 (낮은 인덱스)
    • 양수이면 b가 먼저
    • 0이면 변경하지 않음, 다른 요소에 대한 정렬.

'알고리즘' 카테고리의 다른 글

[boj] 11652. 카드 (node.js)  (0) 2022.01.26