CodeWars 코딩 문제 2021/03/22 - Greed is Good

이호현·2021년 3월 22일
0

Algorithm

목록 보기
92/138

[문제]

Greed is a dice game played with five six-sided dice. Your mission, should you choose to accept it, is to score a throw according to these rules. You will always be given an array with five six-sided dice values.

Three 1's => 1000 points
Three 6's => 600 points
Three 5's => 500 points
Three 4's => 400 points
Three 3's => 300 points
Three 2's => 200 points
One 1 => 100 points
One 5 => 50 point

A single die can only be counted once in each roll. For example, a given "5" can only count as part of a triplet (contributing to the 500 points) or as a single 50 points, but not both in the same roll.

Example scoring

Throw Score


5 1 3 4 1 250: 50 (for the 5) + 2 * 100 (for the 1s)
1 1 1 3 1 1100: 1000 (for three 1s) + 100 (for the other 1)
2 4 4 5 4 450: 400 (for three 4s) + 50 (for the 5)

In some languages, it is possible to mutate the input to the function. This is something that you should never do. If you mutate the input, you will not be able to pass all the tests.

(요약) 주사위를 5번 굴려서 나온 숫자들이 같은게 3번 일 때 위 점수표를 보고 점수를 추가하고, 1이나 5일 때에도 위 점수표를 보고 점수를 추가하라.

[풀이]

function score( dice ) {
  let answer = 0;

  for(let i = 1; i <= 6; i++) {
    if(i === 1) {
      let count = dice.filter(n => n === 1).length;
      answer += count >= 3 ? 1000 + (count - 3) * 100 : count * 100;
    }
    else if(i === 5) {
      let count = dice.filter(n => n === 5).length;
      answer += count >= 3 ? 500 + (count - 3) * 50 : count * 50;
    }
    else {
      dice.filter(n => n === i).length >= 3 && (answer += (`${i}` * 100));  
    }
  }

  return answer;
}

주사위는 1부터 6까지 있으니 for문을 이용해 6번을 돌린다.

숫자가 1, 5, 그 외로 나눠서 조건에 따라 다르게 점수를 구하면 된다.

profile
평생 개발자로 살고싶습니다

0개의 댓글