Algorithm - level1 로또의 최고 순위와 최저 순위

ryan·2022년 5월 12일
0

일부 로또 번호는 알아볼 수 없다. 구매한 로또로 당첨이 가능했던 최고 순위와 최저 순위 구해야 된다. 알아볼 수 없는 번호를 0으로 표기하고, 당첨 가능한 최고 순위와 최저 순위를 배열로 반환한다.

내 풀이(100/100)

function solution(lottos, win_nums) {
  let maximum = 0;
  let minimum = 0;
  let correct = 0;
  let zero = 0;
  let nothing = 0;
  // forEach를 통해 숫자 0, 맞은 번호, 틀린 번호 추출하기
  lottos.forEach((e) => {
    if (e === 0) {
      zero += 1;
      return;
    } else if (win_nums.indexOf(e) > -1) {
      correct += 1;
      return;
    } else {
      nothing += 1;
      return;
    }
  });
  
  // 조건문을 통해 낙첨(2개 이하로 맞추는 경우는 모두 6등)인 경우를 직접 지정
  if (correct < 2 && zero === 0) {
    maximum = 6;
  } else {
    maximum = 6 - correct - zero + 1;
  }
  if (nothing >= 5 || zero >= 5) {
    minimum = 6;
  } else {
    minimum = 6 - correct + 1;
  }
  return [maximum, minimum];
}

다른 사람 풀이 뜯어보기

function solution(lottos, win_nums) {
  // 0과 맞은 숫자 구하기
  const zeroCount = lottos.filter((e) => e === 0).length;
  const matchCount = win_nums.filter((e) => lottos.includes(e)).length;
  
  // 순위를 배열로 직접 지정하여 내 풀이의 조건문을 대신한다. 
  const matchToRank = [6, 6, 5, 4, 3, 2, 1];
  const lowRank = matchToRank[matchCount];
  const highRank = zeroCount === 6 ? 1 : matchToRank[matchCount + zeroCount];

  return [highRank, lowRank];
}

깔끔한 코드로 다시 풀기

function solution(lottos, win_nums) {
  let zero = lottos.filter((e) => e === 0).length;
  let correct = win_nums.filter((e) => lottos.includes(e)).length;
  const Rank = [6, 6, 5, 4, 3, 2, 1];
  let lowRank = Rank[correct];
  let HighRank = Rank[correct + zero];
  return [HighRank, lowRank];
}

처음 알고리즘 문제를 풀었을 때 forEach, reduce, filter, map 등의 배열 함수의 활용이 부족하다는 걸 알게 됐고 이번에는 최대한 의식하면서 풀게됐다. 이번에 느낀 부족한 점은 무분별한 조건문을 넣고 있다면 위와 같이 특정 조건을 아예 변수로 만들어서 비교, 적용하는 방식이 좋다는 것을 깨달았다.

profile
프론트엔드 개발자

0개의 댓글