[백준.S3] - 2503. 숫자야구

Jimin Kwon·2025년 8월 9일

알고리즘

목록 보기
1/13

🏆 알고리즘 문제 풀이

📌 문제 정보


🧐 문제 설명

영수와 민혁이 숫자 야구 게임을 하고 있다.

  • 민혁이 3자리 숫자를 질문
  • 영수는 스트라이크(숫자+위치 일치)와 볼(숫자만 일치) 개수로 답변
  • 모든 질문/답변을 종합하여 가능한 답의 개수를 출력

제한 조건

  • 0이 포함되지 않음
  • 각 자리 숫자는 중복되지 않음

💡 접근 방법

  1. 후보 숫자 생성
    • 123 ~ 987 범위
    • 0 포함, 숫자 중복 있는 경우 제외
  2. 조건 필터링
    • 각 후보 숫자에 대해 모든 질문과 비교
    • 스트라이크 / 볼 계산 후, 조건 불일치 시 제외
  3. 최종 후보 개수 출력

📝 풀이 과정

단계설명
1123~987 범위를 순회하며 후보 생성
20이 포함되거나 중복된 숫자는 제외
3각 후보를 모든 질문과 비교해 조건 일치 여부 확인
4조건을 모두 만족하면 count 증가
5최종 count 출력

입력값 & 출력값


🧑‍💻 코드

import java.util.Scanner;

public class Main {
	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		
		int num = sc.nextInt();
		int[][] info = new int[num][3];
		
		for (int i = 0; i < num; i++) {
			for (int j = 0; j < 3; j++) {				
				info[i][j] = sc.nextInt();
			}
		}		
		
		int count = 0;
		for (int i = 123; i <= 987; i++) {
			int n1 = i / 100;
			int n2 = (i % 100 ) / 10;
			int n3 = (i % 100 ) % 10;
			String s1 = Integer.toString(n1);
			String s2 = Integer.toString(n2);
			String s3 = Integer.toString(n3);
			
			//만약 0이 있거나, 같은 숫자가 있다면 넘기기 
			if ((n1 == 0 || n2 == 0 || n3 == 0) || (n1 == n2 || n2 == n3 || n1 == n3)) {
				continue;
			} else {
				boolean isPossible = true;
				for (int h = 0; h < num; h++) {
					int strikeCount = 0;
					int ballCount = 0;			
					
					if (s1.charAt(0) == Integer.toString(info[h][0]).charAt(0)) strikeCount++;
					else if (Integer.toString(info[h][0]).contains(s1)) ballCount++;

					if (s2.charAt(0) == Integer.toString(info[h][0]).charAt(1)) strikeCount++;
					else if (Integer.toString(info[h][0]).contains(s2)) ballCount++;

					if (s3.charAt(0) == Integer.toString(info[h][0]).charAt(2)) strikeCount++;
					else if (Integer.toString(info[h][0]).contains(s3)) ballCount++;
					
	                if (strikeCount != info[h][1] || ballCount != info[h][2]) {
	                	isPossible = false;
	                    break;
	                }
				}	
				if (isPossible) count++;
			}
		}		
		System.out.println(count);
	}
}

🔍 코드 해설

1. 후보 생성

  • 123~987을 순회하면서 0 포함 여부중복 여부를 먼저 체크
    → 불필요한 비교를 줄임

2. 질문과 후보 비교

  • 후보와 질문을 각 자리수별로 비교
    • 같은 자리, 같은 숫자 → strikeCount++
    • 다른 자리, 같은 숫자 → ballCount++

3. 조건 불일치 시 탈락

  • 스트라이크와 볼 개수가 문제에서 제시한 값과 다르면 즉시 break

4. 가능한 경우 카운트

  • 모든 질문 조건을 만족하는 경우에만 count++

💭 회고

장점

  • 문제 조건을 잘 활용해 불필요한 후보를 조기 탈락시킴

개선 포인트

  • String 변환 대신 자리 비교를 정수로 직접 처리 가능
int n1 = 456 / 100;        // 4
int n2 = (456 / 10) % 10;  // 5
int n3 = 456 % 10;         // 6
  • 이렇게 뽑으면 n1, n2, n3는 전부 int형 숫자이기 때문에 그냥 ==, != 연산으로 자리 비교 가능.
  • 문자로 바꿔서 '4', '5'로 비교할 필요 X
int c1 = 456 / 100;       // 4
int c2 = (456 / 10) % 10; // 5
int c3 = 456 % 10;        // 6

int q1 = 465 / 100;       // 4
int q2 = (465 / 10) % 10; // 6
int q3 = 465 % 10;        // 5

int strike = 0;
int ball = 0;

// 첫 번째 자리 비교
if (c1 == q1) strike++;
else if (c1 == q2 || c1 == q3) ball++;

// 두 번째 자리 비교
if (c2 == q2) strike++;
else if (c2 == q1 || c2 == q3) ball++;

// 세 번째 자리 비교
if (c3 == q3) strike++;
else if (c3 == q1 || c3 == q2) ball++;

0개의 댓글