[wecode] CodeKata Week2 Day2 - half

신혜린·2023년 1월 31일
0

wecode42

목록 보기
18/32
  • 2023.1.31(화) 코드카타 week2 day2

문제

숫자로 이루어진 배열인 nums를 인자로 전달합니다.
숫자중에서 과반수(majority, more than a half)가 넘은 숫자를 반환해주세요.

예를 들어,

nums = [3,2,3]
return 3

nums = [2,2,1,1,1,2,2]
return 2

가정

nums 배열의 길이는 무조건 2개 이상


나의 답

function moreThanHalf(nums) {
  let result = {};
  nums.forEach((x) => {
    if (result[x]) {
      result[x] = result[x] + 1;
    } else {
      result[x] = 0 + 1;
    }
  });
  // console.log(result) // { '2': 1, '3': 2 } forEach문을 통해 객체로 만들어줌
  const resultValue = Object.values(result);
  // console.log(resultValue) // [ 1, 2 ] Object.values문을 통해 Value값만 배열로 추출
  const resultMaxValue = Math.max(...resultValue);
  // console.log(resultMaxValue) // 2 Math.max문을 통해 value배열 속 최대값 추출
  const resultarr = Object.entries(result);
  // console.log(resultarr) // [ [ 'a', 2 ], [ 'b', 1 ] ] Object.entries문을 통해 객체를 배열화 (아래 if문에서의 비교를 위함)

  for (i = 0; i < resultarr.length; i++) {
    if (resultarr[i][1] === resultMaxValue) {
      return Number(resultarr[i][0]);
    }
  }
}

moreThanHalf([3, 2, 3])

module.exports = { moreThanHalf };

nums.forEach((x) => {
    if (result[x]) {
      result[x] = result[x] + 1;
    } else {
      result[x] = 0 + 1;
    }
  });

처음에 배열의 첫번째 값 'a'가 들어오면,
result[x], 즉, result.a는 undefined 입니다.
result.a가 undefined이므로
result에 a 속성을 추가하고, 0+1, 즉, 1을 세팅합니다.

배열의 두번째 값 'b'가 들어와도 마찬가지로
result에 b 속성을 추가하고, 1을 세팅합니다.

배열의 세번째 값 'a'가 들어오면,
이번에는 result.a의 값이 1로 세팅되어 있으므로,
result.a의 값을 result.a + 1, 즉, 1+1, 2로 세팅
합니다.

이런 방법으로 배열의 모든 원소를 대상으로 반복합니다.

💬 result[x] = undefined 라 값이 0이 된다..? 아직까지 아리송한 개념...

profile
개 발자국 🐾

0개의 댓글