🏉 제출
let [n, ...testcase] = require('fs').readFileSync(0).toString().trim().split("\n").map(Number);
testcase = testcase.sort((a, b) => a - b);
// 산술 평균
function sansul(arr, n) {
return Math.round(arr.reduce((a, b) => a + b, 0) / n) + "";
}
// 중앙값
function whatiscenter(arr) {
arr = arr.sort((a, b) => a - b);
let s = Math.floor(arr.length / 2);
return arr[s];
}
// 최빈값
function been(arr) {
let counting = new Map();
let maxBeen = 0;
for (let i of arr) {
counting.set(i, (counting.get(i) || 0) + 1);
maxBeen = Math.max(maxBeen, counting.get(i));
}
let modes = [];
for (let [num, freq] of counting) {
if (freq === maxBeen) modes.push(num);
}
modes.sort((a, b) => a - b);
return modes.length > 1 ? modes[1] : modes[0];
}
// 범위
function inter(arr) {
return Math.max(...arr) - Math.min(...arr);
}
console.log(sansul(testcase, n));
console.log(whatiscenter(testcase));
console.log(been(testcase));
console.log(inter(testcase));
🍝 과정
제출하고 나니 메모리가 에바이긴한데 어쨌든 맞았습니다...
맞는 코드인 줄 알았는데 최빈값 때문에 3번은 더 틀렸다
다음이 틀렸던 최빈값 코드(들)
// 1차 시도
function been(arr) {
let counting = new Map();
let max = 0;
for (let i of arr) {
if (!counting.has(i)) counting.set(i, 0);
counting.set(i, counting.get(i) + 1);
if (counting.get(i) > max) max = counting.get(i);
}
let countArray = [];
for (let [k, v] of counting) {
if (v === max) countArray.push(k);
}
countArray.sort((a, b) => a - b);
return countArray.length > 1 ? countArray[1] : countArray[0];
}
// 2차 시도
function been(arr) {
let counting = new Map();
let maxBeen = 0;
for (let i of arr) {
counting.set(i, (counting.get(i) || 0) + 1);
maxBeen = Math.max(maxBeen, counting.get(i));
}
let modes = [];
for (let [num, freq] of counting) {
if (freq === maxBeen) modes.push(num);
}
modes.sort((a, b) => a - b);
return modes.length > 1 ? modes[1] : modes[0];
}
추가로 0일 때도 고려했어야 하는데 산술평균 값에서 Math.floor로 내려줄때 -0으로 나와서 틀렸던 경우도 있었다.
그래서 산술평균 처리해주는 함수에서 리턴값에 + ''이 있다!
저렇게 함수로 안 만들고 result 변수에 console로 찍을 걸 다 넣어버린다면 출력하는 항목 별로 +=할 떼 +'\n' 해버려도 될 듯?
'baekjoon' 카테고리의 다른 글
| 백준_26069: 붙임성 좋은 총총이 (node.js/JavaScript) (0) | 2024.08.20 |
|---|---|
| 백준_1920: 수 찾기 (node.js/JavaScript) (0) | 2024.08.20 |
| 백준_1735: 분수 합 (node.js/JavaScript) (0) | 2024.08.20 |
| 백준_15649: N과 M (1) (node.js/JavaScript) (0) | 2024.08.13 |
| 백준_25192 : 인사성 밝은 곰곰이 (node.js/JavaScript) (0) | 2024.08.13 |
