Seren dev's blog
article thumbnail

https://www.acmicpc.net/problem/2503

 

2503번: 숫자 야구

첫째 줄에는 민혁이가 영수에게 몇 번이나 질문을 했는지를 나타내는 1 이상 100 이하의 자연수 N이 주어진다. 이어지는 N개의 줄에는 각 줄마다 민혁이가 질문한 세 자리 수와 영수가 답한 스트

www.acmicpc.net

풀이

완전탐색으로 풀었다.

1부터 9까지 서로 다른 숫자 3개로 구성된 세 자리의 숫자가 답에서 말한 조건과 일치하는지 검사하고, 모든 답들과 일치한다면 카운트한다.

코드

import java.util.*;
import java.io.*;

public class Main {
	
	static class Answer {
		String number;
		int strike;
		int ball;
		
		public Answer(String number, int strike, int ball) {
			this.number = number;
			this.strike = strike;
			this.ball = ball;
		}
	}
	
	static ArrayList<Answer> answers = new ArrayList<>();

    public static void main(String[] args) throws IOException {
    	BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
    	int n = Integer.parseInt(br.readLine());
    	
    	for (int i = 0; i < n; i++) {
    		StringTokenizer st = new StringTokenizer(br.readLine());
    		String number = st.nextToken();
    		int strike = Integer.parseInt(st.nextToken());
    		int ball = Integer.parseInt(st.nextToken());
    		
    		answers.add(new Answer(number, strike, ball));
    	}
    	
    	int cnt = 0;
    	
    	// 완전 탐색: 1부터 9까지 서로 다른 숫자 3개로 구성된 세 자리의 숫자가 모든 답들과 매치되는지 체크
    	for (int i = 1; i <= 9; i++) {
    		for (int j = 1; j <= 9; j++) {
    			if (i == j) continue;
    			
    			for (int k = 1; k <= 9; k++) {
    				if (i == k || j == k) continue;
    				
    				int num = 100*i + 10*j + k;
    				
    				if (match(num)) {
    					cnt++;
    				}
    			}
    		}
    	}
    	
    	System.out.println(cnt);
    }
    
    static boolean match(int n) {
    	String num1 = String.valueOf(n);
    	
    	for (Answer answer: answers) {
    		String num2 = answer.number;
    		int strike = 0, ball = 0;
    		
    		for (int i = 0; i < 3; i++) {
    			char ch1 = num1.charAt(i);
    			for (int j = 0; j < 3; j++) {
    				char ch2 = num2.charAt(j);
    				
    				if (ch1 == ch2) {
    					if (i == j) strike++;
    					else ball++;
    					break;
    				}
    			}
    		}
    		
    		if (strike != answer.strike || ball != answer.ball) {
    			return false;
    		}
    	}
    	
    	return true;
    }
}

 

728x90
profile

Seren dev's blog

@Seren dev

포스팅이 좋았다면 "좋아요❤️" 또는 "구독👍🏻" 해주세요!