카카오톡 게임별의 하반기 신규 서비스로 다트 게임을 출시하기로 했다. 다트 게임은 다트판에 다트를 세 차례 던져 그 점수의 합계로 실력을 겨루는 게임으로, 모두가 간단히 즐길 수 있다.
갓 입사한 무지는 코딩 실력을 인정받아 게임의 핵심 부분인 점수 계산 로직을 맡게 되었다. 다트 게임의 점수 계산 로직은 아래와 같다.
"점수|보너스|[옵션]"으로 이루어진 문자열 3세트.
예) 1S2D*3T
점수는 0에서 10 사이의 정수이다.
보너스는 S, D, T 중 하나이다.
옵선은 *이나 # 중 하나이며, 없을 수도 있다.
3번의 기회에서 얻은 점수 합계에 해당하는 정수값을 출력한다.
예) 37
| 예제 | dartResult | answer | 설명 |
|---|---|---|---|
| 1 | 1S2D*3T | 37 | 11 2 + 22 2 + 33 |
| 2 | 1D2S#10S | 9 | 12 + 21 * (-1) + 101 |
| 3 | 1D2S0T | 3 | 12 + 21 + 03 |
| 4 | 1S2T3S | 23 | 11 2 2 + 23 * 2 + 31 |
| 5 | 1D#2S*3S | 5 | 12 (-1) 2 + 21 * 2 + 31 |
| 6 | 1T2D3D# | -4 | 13 + 22 + 32 * (-1) |
| 7 | 1D2S3T* | 59 | 12 + 21 2 + 33 2 |
처음에는 charAt(i)를 사용해서 한 문자씩 가져오려 했으나 점수가 10점까지 있어서 다른 방법이 필요했다.
점수 + 보너스 + [옵션] 패턴이 3번 반복되는데 이런 패턴을 가려낼 수 있다면 편할 것 같았다.
그 방법은 바로 정규식이었다.
아직 정규식이 낯설지만 앞으로 자주 활용될 것 같으니 공부해야겠다.
find()는 문자열에서 해당하는 패턴을 찾고 더 이상 나타나지 않을 때 false를 반환한다. 이 문제에서 while(matcher.find())를 하면 3번의 반복을 얻을 수 있다.
group(1), group(2), group(3)으로 각 게임의 점수,보너스, 옵션을 가져올 수 있다.
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
class Solution {
public int solution(String dartResult) {
int sum = 0;
List<Integer> scores = new ArrayList<>();
int i = 0;
Pattern pattern = Pattern.compile("([0-9]+)([SDT])([*#]?)");
Matcher matcher = pattern.matcher(dartResult);
while(matcher.find()){
int score = Integer.parseInt(matcher.group(1));
String bonus = matcher.group(2);
if(bonus.equals("D")){
score = (int)Math.pow(score, 2);
}else if(bonus.equals("T")){
score = (int)Math.pow(score, 3);
}
String opt = matcher.group(3);
if(opt != null){
if(opt.equals("*")){
if(i > 0){
score += scores.get(i-1);
scores.remove(scores.get(i-1));
}
score *= 2;
}else if(opt.equals("#")){
score *= -1;
}
}
scores.add(score);
i++;
}
for(int s:scores){
sum += s;
}
return sum;
}
}
그런데 테스트 18,22에 런타임 에러가 발생했다.
어느 부분이 문제인지 생각해봐야겠다.
가장 매끄럽지 않은 부분은 스타상(*)을 처리할 때 같다.
바로 전에 얻은 점수를 불러와야 하는데 지금은 리스트에서 불러오고 삭제하는 작업을 거친다.
get,remove를 set으로 바꿔봤다.
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
class Solution {
public int solution(String dartResult) {
int sum = 0;
List<Integer> scores = new ArrayList<>();
int i = 0;
Pattern pattern = Pattern.compile("([0-9]+)([SDT])([*#]?)");
Matcher matcher = pattern.matcher(dartResult);
while(matcher.find()){
int score = Integer.parseInt(matcher.group(1));
String bonus = matcher.group(2);
if(bonus.equals("D")){
score = (int)Math.pow(score, 2);
}else if(bonus.equals("T")){
score = (int)Math.pow(score, 3);
}
String opt = matcher.group(3);
if(opt != null){
if(opt.equals("*")){
if(i > 0){
scores.set(i-1, scores.get(i-1) * 2);
}
score *= 2;
}else if(opt.equals("#")){
score *= -1;
}
}
scores.add(score);
i++;
}
for(int s:scores){
sum += s;
}
return sum;
}
}
이렇게만 바꿔도 잘 작동된다.
다른 사람들은 stack으로도 구현하는 것 같다.
pop을 한 후 다시 push를 하면 전의 값을 쉽게 불러오고 저장할 수 있다.