프로그래머스 LEVEL 1(다트 게임)

image

  • 사용 언어 : javascript

  • 해결 날짜 : 2022-08-18

  • 해결 방법 :

    • switch문으로 각 case 별 처리
    • 획득 점수가 10인 경우 처리하기 위해 index - 1, - 2 숫자인지 체크
  • 회고 :
    • 정규식으로 해결하기
  • 코드
  function solution(dartResult) {
      const arr = [...dartResult];
      const points = [];
      for (const [index, value] of arr.entries()) {
          if (isNaN(value)) {
              const point = (!isNaN(arr[index - 1]) && !isNaN(arr[index - 2])) ? 10 : Number(arr[index - 1]);
              switch(value) {
                  case 'S':
                      points.push(point);
                      break;
                  case 'D':
                      points.push(Math.pow(point, 2));
                      break;
                  case 'T':
                      points.push(Math.pow(point, 3));
                      break;
                  case '*':
                      const length = points.length;
                      points[length - 1] *= 2;
                      if (length > 1) points[length - 2] *= 2;
                      break;
                  case '#':
                      points[points.length - 1] = -points[points.length - 1];
                      break;
                  default:
                      break;
              }
          }
      }
      return points.reduce((acc, cur) => {
          return acc + cur;
      }, 0);
  }