[Lv.0] 최빈값 구하기 **

01수정·2022년 11월 10일
0
post-thumbnail

<입문 100문제> Day 3 - 사칙연산, 배열, 수학

문제



풀이

function solution (array) {
    let dictionary = array.reduce((dic, num) => (dic[num] ? {...dic, [num]: dic[num]+1} : {...dic, [num]: 1}), {})
    let max = Math.max(...Object.values(dictionary))
    let mostRecent = Object.keys(dictionary).filter(key => dictionary[key] === max)
    return mostRecent.length === 1 ? +mostRecent : -1
}

해답

function solution(array) {
  const counts = array.reduce((a, c) => (a[c] ? { ...a, [c]: a[c] + 1 } : { ...a, [c]: 1 }), {});
  const max = Math.max(...Object.values(counts));
  const modes = Object.keys(counts).filter(key => counts[key] === max);
  return modes.length === 1 ? +modes[0] : -1;
}

해답풀이

(1) array의 값을 reduce 로 돌며 {숫자: 개수, 숫자: 개수, ...} 형식의 dictionary 생성

const counts = array.reduce((a, c) => (a[c] ? { ...a, [c]: a[c] + 1 } : { ...a, [c]: 1 }), {});

(2) (1) 의 dictionary 의 모든 values(개수)을 나열한 후 최대값 추출

const max = Math.max(...Object.values(counts));

(3) (1) 의 dictionary 의 모든 key(숫자)를 하나씩 순회하며 (2)에서 구한 최대값과 key 의 value(=dictionary[key]) 가 동일하면 mostRecent 에 넣기

let mostRecent = Object.keys(dictionary).filter(key => dictionary[key] === max)

참고자료

profile
새싹 FE 개발자

0개의 댓글