SWEA(SW Expert Academy) 20934. 방울 마술 D3

heesan·2024년 9월 14일

코딩테스트

목록 보기
15/40

●문제 출처

https://swexpertacademy.com/main/code/problem/problemDetail.do?problemLevel=3&contestProbId=AY9QTGqqcckDFAVF&categoryId=AY9QTGqqcckDFAVF&categoryType=CODE&problemTitle=&orderBy=FIRST_REG_DATETIME&selectCodeLang=ALL&select-1=3&pageSize=10&pageIndex=1&&&&&&&&&&

●정리(요약)

일렬의 3개의 컵 하나에 방울을 넣고 섞는다.

(한 번 섞는 것은 인접한 두 컵을 교환하는 것)

컵을 섞을 때마다

동전 앞면이 나오면 왼쪽 컵과 가운데 컵의 순서를 바꿈

동전 뒷면이 나오면 오른쪽 컵과 가운데 컵의 순서를 바꿈

(동전 확률은 1/2)

방울이 들어 있는 컵을 교환할 때마다 방울이 한 번씩 울린다.

(울림 횟수 k)

현재 방울이 있을 확률이 가장 높은 컵의 위치를 구하라

<입력>

테스트 케이스 T

컵 위치 S(. 빈 컵 , o 방울이 들어있는 컵) k(0≤K≤1,000)

<출력>

맨 왼쪽이라면 0,

가운데라면 1,

맨 오른쪽이라면 2




●코드

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.StringTokenizer;
  
 
class Solution
{
 
    public static void main(String args[])throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        StringBuilder sb = new StringBuilder();
        StringTokenizer st;
 
        int T = Integer.parseInt(br.readLine());  
 
        for (int i = 1; i <= T; i++) {
            st = new StringTokenizer(br.readLine(), " ");
             
            String S = st.nextToken(); 
            int k = Integer.parseInt(st.nextToken());  
             
            int currentPosition = S.indexOf("o");  
            int newPosition = calculateNewPosition(currentPosition, k);  
             
            sb.append("#").append(i).append(" ").append(newPosition).append("\n");
        }
 
        System.out.println(sb.toString());
    }
 
   
    private static int calculateNewPosition(int currentPosition, int moves) {
        if (moves == 0) {
            return currentPosition; 
        }
 
        if (currentPosition == 0 || currentPosition == 2) {
            // 'o'가 양 끝에 있는 경우
            return (moves % 2 == 0) ? 0 : 1;  // 짝수면 0, 홀수면 1로 이동
        } else if (currentPosition == 1) {
            // 'o'가 가운데 있는 경우
            return (moves % 2 == 0) ? 1 : 0;  // 짝수면 1, 홀수면 0으로 이동
        }
 
        return currentPosition;
    }
}

●느낀 점

처음에는 그냥 경우에 수를 다 계산해 보자 하여 DFS(Depth-First Search) 방식에 가깝게 풀었다..

하지만 시간 초과로 떠서 노트에 직접 경우에 수를 계산해 보고 'o'가 양 끝에 있는 경우 짝수 면 0에 홀수 면 1에

'o'가 중앙에 위치하면 짝수 면 1에 홀수 면 0에 위치한다는 사실을 알았다.

처음부터 노트에 경우의 수를 적으면 30분 안에 풀었을 거 같은데...

다음부터는 규칙을 알아내야겠다.

profile
👩‍💻Backend Engineering

0개의 댓글