스파르타코딩클럽 내일배움캠프 TIL8

한재창·2022년 11월 10일
0

알고리즘

알고리즘 수업을 듣고 파이썬이 아닌 자바스크립트로, 나만의 해결책으로 최빈값 문제를 풀어봤다. 굉장히 오랜시간이 걸렸고 이해하는데도 오래 걸렸지만 내가 풀었다는 성취감에 만족한다!

// 방법1
const input = "aaacbdac";

function solution(inputString) {
  const findObject = {};
  for (let inputS of inputString) {
    if (inputS in findObject) {
      findObject[inputS] += 1;
    } else {
      findObject[inputS] = 1;
    }
    console.log(findObject);
  }
  const maxValue = Math.max.apply(null, Object.values(findObject));
  console.log(Object.keys(findObject));
  const result = Object.keys(findObject).find((key) => {
    // 조건값에 맞는 키를 반환하다.
    return findObject[key] === maxValue;
  });
  return result;
}
console.log(solution(input));

// 방법2

const solution1 = (inputString) => {
  const inputStringObject = inputString.reduce((acc, currentValue) => {
    if (currentValue in acc) {
      acc[currentValue] += 1;
    } else {
      acc[currentValue] = 1;
    }
    return acc;
  }, {});
  const maxValue = Math.max.apply(null, Object.values(inputStringObject));
  const result = Object.keys(inputStringObject).find((key) => {
    return inputStringObject[key] === maxValue;
  });
  return result;
};

console.log(solution1(input.split("")));
profile
취준 개발자

0개의 댓글

관련 채용 정보