프로그래머스 다트게임 : https://programmers.co.kr/learn/courses/30/lessons/17682
풀이 과정보다는 자잘한 버그(배열 인덱스가 1부터 시작하는 코드 짠 거 실화냐..)에 더 많은 시간이 걸렸다..
함수를 분리하려고 했는데 가독성 면에서는 잘 모르겠다. 어떤 방식이 효율적인지는 좀 더 찾아봐야할 것 같다.
라운드가 단순히 3 라운드밖에 없어서 하드코딩을 한 점이 없지않아 있는데, 이게 확장될 경우의 수도 생각해야할 것 같다.
function solution(dartResult) {
let roundScore = [];
let temp = "";
for (let letter of dartResult) {
if (letter === "S" || letter ==="D" || letter === "T") {
let basicScore = getBasicScore(temp, letter);
roundScore.push(basicScore);
temp = "";
} else if (letter === "*" || letter === "#") {
applyOption(roundScore, letter);
temp = "";
} else {
temp += letter;
}
}
return roundScore.reduce((a, c) => a + c);
}
// 보너스를 계산하는 함수
function getBasicScore(score, bonus) {
let roundScore = 0;
// score을 number로 변환
score = +score;
// 라운드 점수 계산
if (bonus === "S") roundScore = Math.pow(score, 1);
if (bonus === "D") roundScore = Math.pow(score, 2);
if (bonus === "T") roundScore = Math.pow(score, 3);
return roundScore;
}
// 옵션을 계산하는 함수
function applyOption(roundScore, option) {
let length = roundScore.length;
if (option === "*") {
roundScore.forEach((score, index) => {
if (!(length === 3 && index === 0)) {
roundScore[index] *= 2;
}
})
}
if (option === "#") {
roundScore[length - 1] *= -1;
}
}
리팩토링하면서 변수명도 고치고 하드코딩한 부분의 확장성도 고쳤다. 이제 다른 사람들 코드 보러 가야지!
function solution(dartResult) {
let roundScore = [];
let score = "";
for (let letter of dartResult) {
if (letter === "S" || letter ==="D" || letter === "T") {
let basicScore = applyBonus(score, letter);
roundScore.push(basicScore);
score = "";
}
else if (letter === "*" || letter === "#") {
let curRoundIndex = roundScore.length - 1;
applyOption(roundScore, curRoundIndex, letter);
}
else {
score += letter;
}
}
return roundScore.reduce((a, c) => a + c);
}
function applyBonus(score, bonus) {
if (bonus === "S") return Math.pow(+score, 1);
if (bonus === "D") return Math.pow(+score, 2);
if (bonus === "T") return Math.pow(+score, 3);
}
function applyOption(roundScore, curRoundIndex, option) {
let length = roundScore.length;
if (option === "*") {
roundScore[curRoundIndex] *= 2;
if (curRoundIndex - 1 >= 0) roundScore[curRoundIndex - 1] *= 2
}
if (option === "#") {
roundScore[length - 1] *= -1;
}
}
for (let i = 0; i < dartResult.length; i++) {
// 점수가 10인 경우의 수
if (dartResult[i + 1] === "0") {
temp = dartResult[i] + dartResult[i + 1];
i++
}
}
for (let i = 0; i < dartResult.length; i++) {
// 점수 추출하기
// 보너스 추출하기
if (dartResult[i + 1] === "S" || /* 기타 생략 */) {
/* 대충 보너스 계산 */
i++;
}
// 옵션 추출하기
if (dartResult[i + 1] === "#" || /* 기타 생략 */) {
/* 대충 옵션 계산 */
i++;
}
}
var dr = dartResult.match(/\d{1,2}[SDT]{1}[*|#]?/g )
// 출처: https://jo-c.tistory.com/23 [조씨의 개발 블로그]
let score = {S : 1, D : 2, T : 3}; //영역에 따른 제곱 수
let data = dartResult.charAt(i);
stack.push(Math.pow(dartResult.slice(i - count, i), score[data]));
// 출처 : https://akh95123.blogspot.com/2019/11/javascript_12.html