华为OD机试-2024年E卷-猜数字[100分] JAVA

暴力破解:

 public static void main(String[] args) throws IOException {
        BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
        int n = Integer.parseInt(reader.readLine());
        String[] guesses = new String[n];
        int[][] hints = new int[n][2];
        for (int i = 0; i < n; i++) {
            String[] line = reader.readLine().split(" ");
            guesses[i] = line[0];
            String[] strs =  line[1].replace("A"," ").replace("B", " ").split(" ");
            hints[i][0]= Integer.parseInt(strs[0]);
            hints[i][1]= Integer.parseInt(strs[1]);
        }
        int validCount = 0;
        String answer = "";

        // 遍历所有可能的四位数
        for (int num = 0; num < 10000; num++) {
            String temp = String.format("%04d", num);
            boolean isValid = true;


            // 检查当前数字是否符合所有猜测的提示
            for (int i = 0; i < n; i++) {
                if (!check(temp, guesses[i], hints[i][0], hints[i][1])) {
                    isValid = false;
                    break;
                }
            }

            if (isValid) {
                validCount++;
                answer = temp;
                if (validCount > 1) {
                    break;
                }
            }
        }

        if (validCount == 1) {
            System.out.println(answer);
        } else {
            System.out.println("NA");
        }

    }

    // 检查当前猜测与谜底是否匹配
    public static boolean check(String target, String guess, int a, int b) {
        int correctPosition = 0;
        int correctNumberWrongPosition = 0;
        boolean[] usedTarget = new boolean[4];
        boolean[] usedGuess = new boolean[4];

        // 统计位置和数字都正确的数量
        for (int i = 0; i < 4; i++) {
            if (target.charAt(i) == guess.charAt(i)) {
                correctPosition++;
                usedTarget[i] = true;
                usedGuess[i] = true;
            }
        }

        // 统计数字正确但位置不正确的数量
        for (int i = 0; i < 4; i++) {
            if (!usedGuess[i]) {
                for (int j = 0; j < 4; j++) {
                    if (!usedTarget[j] && guess.charAt(i) == target.charAt(j)) {
                        correctNumberWrongPosition++;
                        usedTarget[j] = true;
                        break;
                    }
                }
            }
        }

        return correctPosition == a && correctNumberWrongPosition == b;
    }
全部评论

相关推荐

每晚夜里独自颤抖:要求太多的没必要理
点赞 评论 收藏
分享
05-05 21:45
已编辑
广州大学 Java
点赞 评论 收藏
分享
评论
点赞
1
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务