πŸ”₯ Algorithm/Baekjoon

[λ°±μ€€ 2108번] 톡계학 - μžλ°”μŠ€ν¬λ¦½νŠΈ(nodejs)

Lennon 2022. 5. 3. 18:52
728x90
λ°˜μ‘ν˜•

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

 

2108번: 톡계학

첫째 쀄에 수의 개수 N(1 ≤ N ≤ 500,000)이 주어진닀. 단, N은 ν™€μˆ˜μ΄λ‹€. κ·Έ λ‹€μŒ N개의 μ€„μ—λŠ” μ •μˆ˜λ“€μ΄ 주어진닀. μž…λ ₯λ˜λŠ” μ •μˆ˜μ˜ μ ˆλŒ“κ°’μ€ 4,000을 λ„˜μ§€ μ•ŠλŠ”λ‹€.

www.acmicpc.net

const readline = require('readline');

const rl = readline.createInterface({
  input: process.stdin,
  output: process.stdout,
});
let input = [];
rl.on('line', function (line) {
  input.push(line);
  if (input.length === +input[0] + 1) {
    rl.close();
  }
}).on('close', function () {
  const [N, ...nums] = input.map(Number);

  nums.sort((a, b) => a - b);

  const avg = Math.round(nums.reduce((acc, cur) => acc + cur, 0) / nums.length);
  const median = nums[Math.floor(nums.length / 2)];

  const obj = {};

  for (let i = 0; i < N; i++) {
    if (!obj[nums[i]]) {
      obj[nums[i]] = 1;
    } else {
      obj[nums[i]] += 1;
    }
  }
  const modeArr = Object.entries(obj).sort((a, b) => b[1] - a[1]);
  const value = modeArr[0][1];

  console.log(avg === 0 ? +0 : avg);
  console.log(median);
  if (nums.length > 1 && modeArr[1][1] === value) {
    const maxModeArr = modeArr.filter((v) => v[1] === value);
    maxModeArr.sort((a, b) => +a[0] - +b[0]);
    console.log(+maxModeArr[1][0]);
  } else {
    console.log(+modeArr[0][0]);
  }
  if (nums.length > 1) {
    console.log(Math.abs(nums[nums.length - 1] - nums[0]));
  } else {
    console.log(0);
  }
});

μ΅œλΉˆκ°’μ—μ„œ 정렬을 잘 ν•˜λŠ” 것을 μ°ΎλŠ”κ²Œ 쀑점이닀! - 본인은 정렬을 μ•ˆ ν•œ μƒνƒœμΈμ§€ λͺ¨λ₯΄κ³  μ–΄λ””κ°€ 틀린지 찾느라 κ³ μƒν–ˆλ‹€

728x90
λ°˜μ‘ν˜•