[ 정규식 ] - 다트 게임
https://programmers.co.kr/learn/courses/30/lessons/17682#
코딩테스트 연습 - [1차] 다트 게임
programmers.co.kr
이번에도 물론 100점이 안나왔다. 84점인가?
어느부분에 틀린부분을 접근해야하는지 감이안온다.
풀이식은 이번에도 최대한 정규식을 활용해봥ㅆ다
reg 에 적었다
첫자리는 0~10
둘째자리는 알파멧 대문자
세번재자리는 *or # 이 올수도있고 안올수도 있다
위의 세가지조건을 충족하는 string이 들어올것이다
그 아래에는 그냥 조건에 맞는 점수 충족 식을 작성하였다.
import java.util.ArrayList;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
class Solution {
public int solution(String dartResult) {
ArrayList<obj> totalObj = new ArrayList<obj>();
String reg="(([0-9]|10)[A-Z][*#]?)";
Pattern pattern=Pattern.compile(reg);
Matcher matcher = pattern.matcher(dartResult);
int startNum=0;
while(matcher.find()) {
obj word = new obj(matcher.group(),startNum,totalObj);
totalObj.add(word);
startNum++;
if(startNum==3) break;
}
double totalP=0;
for(int i =0 ; i < totalObj.size() ; ++i ){
totalP+=totalObj.get(i).totalP;
}
int answer = (int)totalP;
return answer;
}
}
class obj{
ArrayList<obj> totalObj=null; //total 점수 리스트
int startNum; // 몇번재 다트인지 체크
int num; // 다트 점수 0~10
String SDT; // 보너스
String option; //옵션
double normalP; // 옵션 제외한 점수
double totalP; //옵션 보함한 점수
public obj(String c, int startNum,ArrayList<obj> totalObj){
this.totalObj = totalObj;
this.startNum=startNum;
//10인경우
if((c.substring(0,2)).contentEquals("10")){
this.num = Integer.parseInt(c.substring(0,2));
this.SDT = c.substring(2,3);
if(c.length()==4){
this.option = c.substring(3,4);
}
}else{
//10이 아닌경우
this.num = Integer.parseInt(c.substring(0,1));
this.SDT = c.substring(1,2);
if(c.length()==3){
this.option = c.substring(2,3);
}
}
calc();
}
public void calc(){
//일반점수 구하기
double pow=1;
if(SDT.contentEquals("S")) pow = 1;
else if(SDT.contentEquals("D")) pow = 2;
else if(SDT.contentEquals("T")) pow = 3;
this.normalP= Math.pow((double)num,pow);
//옵션 점수 구하기
if(option!=null){
//첫번째 던진 경우
if(startNum==0){
if(option.contentEquals("*")){
totalP=normalP*2;
}else{
totalP=normalP*(-1);
}
}
else{
// 두번째 세번째 인경우
//앞에 문자에 옵션이 있는지 먼저 체크
if(totalObj.get(startNum-1).option!=null){
if(option.contentEquals("*")){
totalP=normalP*2;
totalObj.get(startNum-1).totalP =totalObj.get(startNum-1).totalP*2;
}else if(option.contentEquals("#")){
totalP=normalP*(-2);
}
}
else{
//앞에 다트의 옵션이 없엇음으로 현재 옵션만 적용
if(option.contentEquals("*")){
totalP=normalP*2;
totalObj.get(startNum-1).totalP =totalObj.get(startNum-1).totalP*2;
}else if(option.contentEquals("#")){
totalP=normalP*(-1);
}
}
}
}else{
totalP=normalP;
}
}
}
언제쯤 .. 주어진 시간에 100점을 맞을수 있을련지..