-
[JS] 다트 게임 (1차)이노베이션 캠프/3주차_알고리즘 2023. 6. 21. 14:32
문제
https://school.programmers.co.kr/learn/courses/30/lessons/17682
문제 풀이
function solution(dartResult) { let result = []; // 1) 결과 값을 저장한 변수 선언 및 할당 let pat = /\d+[A-Z][*#]?/g; // 2) 값을 잘라올 수 있는 패턴 생성 let gameResults = dartResult.match(pat); // 3) match 사용하여 생성된 패턴과 일치하는 문자열 배열로 저장 let i = 0; // 4) 현재 인덱스 정보 저장한 변수 선언 및 생성 let scorePat = /\d+/g; // 5) 점수 패턴 생성 let bonusPat = /[A-Z]/g; // 6) 보너스 패턴 생성 let optPat = /\*|\#/g; // 7) 옵션 패턴 생성 // 8) for of문 사용하여 배열 내 모든 요소에 접근 for (game of gameResults){ let score = game.match(scorePat)[0]; // 9) 패턴 사용하여 점수 가져오기 let bonus = game.match(bonusPat)[0]; // 10) 패턴 사용하여 보너스 가져오기 let opt = game.match(optPat); // 11) 패턴 사용하여 옵션 가져오기 let option = (game.match(optPat)) ? opt[0]: ""; // 12) 옵션은 있을 수도 없을 수도 있음, 있는 경우 옵션 값 아니면 빈 문자열 저장 // 13) 보너스 값 확인하여 제곱근으로 넣어줄 값 결정 let n = 1; // 기본으로 S의 값을 넣어줌 if (bonus === "D") n = 2; else if (bonus === "T") n = 3; let num = Math.pow(score, n); // 14) 옵션이 존재하는 경우 아래 로직 수행 if (option === "*") { // 스타상: 이전 값, 현재 값 모두 2배 num *= 2; // 14-1) 현재 값 2배 if (i > 0) { // 14-2) 이전 값 2배 (이전 값이 존재하는 경우에만) let t = result[i-1] * 2; result[i-1] = t; } } else if (option === "#") { // 아차상: 음수 값으로 변함 num = -num; // 14-3) 양수에서 음수로 변경 } result.push(num); i++; // 15) 현재 배열의 인덱스 증가 } // 16) reduce 메소드 사용하여 전체의 합 구해서 리턴 return result.reduce((a, b) => a + b); }
참고 사이트
https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce
728x90'이노베이션 캠프 > 3주차_알고리즘' 카테고리의 다른 글
[JS] 실패율 (0) 2023.06.21 [JS] 크레인 인형뽑기 게임 (0) 2023.06.21 [JS] 비밀지도 (0) 2023.06.21 [JS] 폰켓몬 (0) 2023.06.21 [JS] 소수 찾기 (0) 2023.06.21