[Programmers] [1차] 다트 게임 - 2018 KAKAO BLIND RECRUITMENT

동민·2021년 3월 10일
0
import java.util.ArrayList;

// [1차] 다트 게임 - 2018 KAKAO BLIND RECRUITMENT
public class DartsGame {
	public int solution(String dartResult) {
		int answer = 0;

		ArrayList<String> list = new ArrayList<>(); // 문자열을 숫자, 문자, 특수문자로 구분하여 넣을 리스트
		ArrayList<Integer> scoreList = new ArrayList<>(); // 각 회차 점수를 저장할 리스트

		int index = 0;
		char temp;
		for (int i = 1; i <= dartResult.length(); i++) { // 리스트에 숫자, 문자, 특수문자를 구분하여 add함; 숫자가 아닌 문자가 나올때까지 i를 늘려 substring으로 숫자만 걸러냄

			temp = dartResult.charAt(i - 1); // temp에 반복되는 계산식을 저장함으로써 불필요한 중복계산을 줄여 속도를 높임
			if (!(temp >= '0' && temp <= '9')) {

				if (temp != '#' && temp != '*') {
					list.add(dartResult.substring(index, i - 1));
				}
				list.add(temp + "");
				index = i;
			}
		}
		System.out.println(list + "    - list");

		for (int i = 1; i < list.size(); i++) {

			if (list.get(i).equals("S")) {
				scoreList.add((int) Math.pow(Integer.parseInt(list.get(i - 1)), 1)); // 'S' 일때 1승

			} else if (list.get(i).equals("D")) {
				scoreList.add((int) Math.pow(Integer.parseInt(list.get(i - 1)), 2)); // 'D' 일때 2승

			} else if (list.get(i).equals("T")) {
				scoreList.add((int) Math.pow(Integer.parseInt(list.get(i - 1)), 3)); // 'T' 일때 3승

			} else if (list.get(i).equals("*")) {
				scoreList.set(scoreList.size() - 1, scoreList.get(scoreList.size() - 1) * 2); // '*' 일때 바로 직전 점수까지 x2배
				if (scoreList.size() >= 2) { // 만약 scoreList의 사이즈가 1인데 직전 점수까지 x2하려고 scoreList.set() 함수에서 scoreList.size()-2 로 인덱스를 건드리면 IndexOutOfBoundsException 예외가 발생하므로 예외처리 해줘야함
					scoreList.set(scoreList.size() - 2, scoreList.get(scoreList.size() - 2) * 2); 
				}
			} else if (list.get(i).equals("#")) {
				scoreList.set(scoreList.size() - 1, scoreList.get(scoreList.size() - 1) * -1); // '#' 일때 x(-1); scoreList.get() 함수에서 인덱스를 scoreList.size()로 조절하는 이유는 인덱스를 i로 조절 했을 때 list의 인덱스와 scoreList의 인덱스가 맞지 않기 때문에 scoreList.size()를 통해 인덱스를 조절해야 IndexOutOfBoundsException 예외가 발생안함 (위 for문의 범위는 list.size() 까지 반복이나 scoreList의 크기는 1~3회차의 점수를 저장한 리스트기 때문에 크기,인덱스가 다름)
			}
		}
		System.out.println(scoreList + "           - scoreList");

		// for-each statement
		for (int ele : scoreList) { // scoreList에 저장된 각 회차 점수를 모두 더하면 총 점수가 됨
			answer += ele;
		}

		return answer;
	}

	public static void main(String[] args) {

		DartsGame s = new DartsGame();

		System.out.println(s.solution("1S2D*3T")); // 37 = (1^1 + 2^2) * 2 + 3^3
		System.out.println(s.solution("1D2S#10S")); // 9 = 1^2 + 2^1 * (-1) + 10^1
		System.out.println(s.solution("1D2S0T")); // 3 = 1^2 + 2^1 + 0^3
		System.out.println(s.solution("1S*2T*3S")); // 23 = ( 1^1 * 2 + 2^3 ) * 2 + 3^1
		System.out.println(s.solution("1D#2S*3S")); // 5 = (1^2 * -1 + 2^1 ) * 2 + 3^1
		System.out.println(s.solution("1T2D3D#")); // -4 = 1^3 + 2^2 + 3^2*-1
		System.out.println(s.solution("1D2S3T*")); // 59 = 1^2 + (2^1 + 3^3) * 2

	}

}
profile
BE Developer

0개의 댓글

관련 채용 정보