728x90

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

😢 알고리즘을 단계별로 풀었다면, 앞의 지식들을 이용해서 풀어주면 쉽게 가능하다.
코드가 조금 긴 것 같아서, Code Refactoring이 가능할지 고민해 봐야겠다.

😊
산술 평균: arr.reduce함수로 값을 더하고, 2로 나눈 후 Math.round()로 반올림 해주면 된다.
중앙 값: 입력받은 값은 sort()해준 후, Math.floor(arr.length / 2) 해준 것을 index로 넣어주면 된다.
최빈 값: 빈도 별로 Map 생성 - arr.push(최빈 값) - 여러개라면 sort 후(Map을 생성하면서 순서가 바뀌기 때문) index 1(2번 째니까)
아니라면 index 0(1개니까)
범위: sort된 입력값의 마지막 인덱스(arr.length-1) - 입력값의 첫 번째 인덱스(0) 해주면 된다.

// Statistics
// For submit
// const fs = require('fs');
// const input = fs.readFileSync('/dev/stdin').toString().trim().split('\n').map(num => parseInt(num));
// For local test
// const input = [5, 1, 3, 8, -2, 2];
// const input = [1, 4000];
const input = [5, -1, -2, -3, -1, -2];
const N = input.shift();
const sortedNumArr = input.sort((a, b) => a - b);
const numMap = {};
for (let num of sortedNumArr) {
if (numMap[num]) {
numMap[num] = numMap[num] + 1;
} else {
numMap[num] = 1;
}
}
let hitMaxNum = Math.max.apply(null, Object.values(numMap));
let hitMaxNumArr = [];
let hitMaxNumResult = 0;
for (let numKey in numMap) {
if (numMap[numKey] === hitMaxNum) {
hitMaxNumArr.push(numKey);
}
}
if (hitMaxNumArr.length > 1) {
hitMaxNumArr = hitMaxNumArr.sort((a, b) => a - b);
hitMaxNumResult = hitMaxNumArr[1];
} else {
hitMaxNumResult = hitMaxNumArr[0];
}
const avg = Math.round(input.reduce((acc, num) => (acc += num), 0) / N);
const center = input[Math.floor(input.length / 2)];
const maxSubMin = sortedNumArr[sortedNumArr.length - 1] - sortedNumArr[0];
console.log(avg);
console.log(center);
console.log(hitMaxNumResult);
console.log(maxSubMin);
view raw bj_js2108.js hosted with ❤ by GitHub

+ Recent posts