백준 Chop Cup

KIMYEONGJUN·2026년 1월 31일
post-thumbnail

문제

내가 생각했을때 문제에서 원하는부분

The first and only line contains a string of at most 50 characters, Oisín's moves.
Each of the characters is 'A', 'B' or 'C' (without quote marks).

Output the index of the cup under which the ball is: 1 if it is under the left cup, 2 if it is under the middle cup or 3 if it is under the right cup.

내가 이 문제를 보고 생각해본 부분

ballPosition 변수는 공이 어느 컵 아래에 있는지 나타냅니다. 처음에는 왼쪽 컵인 1로 초기화한다.
문자열에서 각각의 문자(이동 명령)를 하나씩 읽는다.
각 이동 명령에 대해 공이 위치한 컵이 스왑 대상이면 위치를 맞바꾼다.
예를 들어, 'A' 명령은 왼쪽(1)과 중간(2)을 교환하므로 공이 1이면 2로, 2이면 1로 바꾼다.
모든 명령을 처리한 뒤에 남은 공의 위치를 출력한다.
마지막에 사용한 BufferedReader를 닫아 자원 누수를 방지한다.

코드로 구현

package baekjoon.baekjoon_32;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

// 백준 13224번 문제
public class Main1284 {
    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

        String moves = br.readLine();
        int ballPosition = 1; // 공은 처음에 1번 컵 아래

        for (int i = 0; i < moves.length(); i++) {
            char move = moves.charAt(i);

            if (move == 'A') {
                // 1과 2 스왑
                if (ballPosition == 1) ballPosition = 2;
                else if (ballPosition == 2) ballPosition = 1;

            } else if (move == 'B') {
                // 2와 3 스왑
                if (ballPosition == 2) ballPosition = 3;
                else if (ballPosition == 3) ballPosition = 2;

            } else if (move == 'C') {
                // 1과 3 스왑
                if (ballPosition == 1) ballPosition = 3;
                else if (ballPosition == 3) ballPosition = 1;
            }
        }

        System.out.println(ballPosition);
        br.close();
    }
}

마무리

코드와 설명이 부족할수 있습니다. 코드를 보시고 문제가 있거나 코드 개선이 필요한 부분이 있다면 댓글로 말해주시면 감사한 마음으로 참고해 코드를 수정 하겠습니다.

profile
Junior backend developer

0개의 댓글