[코드트리] 숫자카운트

h_jin·2025년 3월 12일

코테

목록 보기
25/33

문제링크

문제

야구게임과 비슷한거 같은데
1~9까지 겹치지 않는 수의 조합으로 3자리가 주어지고
자리와 숫자가 일치하는 개수와 숫자만 일치하는 개수가 주어진다
이때 결정될 수 있는 숫자의 개수를 구하여라

예시
4
123 1 1
356 1 0
327 2 0
489 0 1

위의 경우 정답은 324, 328중 하나이므로 2를 리턴하게 된다.

풀이

  • 가능한 모든 수를 주어진 조건에 대입하기
import java.util.Scanner;
public class Main {
    public static int[] num;
    public static int[] count1;
    public static int[] count2;
    public static int n;

    public static boolean checkSame(int i, int a){
        String str = String.valueOf(num[i]);
        String tmp = String.valueOf(a);
        
        int cnt = 0;

        for (int x = 0; x < 3; x++){
            if (str.charAt(x) == tmp.charAt(x))
                cnt++;
        }

        return cnt == count1[i];
    }

    public static boolean checkHave(int i, int a){
        String str = String.valueOf(num[i]);
        String tmp = String.valueOf(a);

        int cnt = 0;

        for (int x = 0; x < 3; x++){
            for (int y = 0; y < 3; y++){
                if (x != y && str.charAt(x) == tmp.charAt(y))
                    cnt++;
            }
        }

        return cnt == count2[i];
    }
    
    public static boolean isValid(int x){
        String str = String.valueOf(x);

        if (str.charAt(0) == str.charAt(1) || str.charAt(0) == str.charAt(2)
            || str.charAt(1) == str.charAt(2))
                return false;
        
        if (str.charAt(0) == '0' || str.charAt(1) == '0' || str.charAt(2) == '0')
            return false;

        for (int i = 0; i < n; i++){
            if (!checkSame(i, x) || !checkHave(i, x))
                return false;
        }
        return true;
    }

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        n = sc.nextInt();
        num = new int[n];
        count1 = new int[n];
        count2 = new int[n];
        for (int i = 0; i < n; i++) {
            num[i] = sc.nextInt();
            count1[i] = sc.nextInt();
            count2[i] = sc.nextInt();
        }
    
        int res = 0;
        for (int i = 123; i <= 987; i++){
            if (isValid(i))
                res++;
        }

        System.out.print(res);
    }
}

0개의 댓글