我似乎无法弄清楚为什么有时我在mastermind中检查白人的代码会计算一个值两次。我的意思是,它以白色和黑色来计算值。但是,有时它可以完美运行,但并不是每次单击都会发现该bug,我找不到原因。

这是我的方法compare(),它将我的两个数组guess []与玩家输入的值进行比较,并将solution []与随机值进行比较。

public void comparaison(){
    white = 0;
    black = 0;
    test = new boolean[columns];
    for(int x = 0 ; x < test.length ; x++){
        test[x] = false;
    }
    for (int i =0 ; i<columns; i++){
        System.out.println(solution[i]);
        if (solution[i] == guess[i]){
            test[i] = true;
            black++;
        }else{
            for (int j=0;j < columns;j++){
                if(!test[j] && j!=i && guess[j] == solution[i]){
                    white++;
                    test[j]=true;
                    break;
                }
            }
        }
    }

    System.out.println("black"+black);
    System.out.println("white"+white);


}

这2个数组之前已声明和初始化,当玩家单击代表颜色的按钮时,它们会被填充(请参见image)。 test []数组也是在之前声明的。

最佳答案

如果您在正确放置的颜色之前放错了颜色,则会出现问题,例如:

           1 2 3 4
Solution : A A B B
Guess    : B B B B



1:B将白与3相匹配
2:B用4匹配白色
3:B再次将黑色和3配对
4:B再次将黑色和4配对


您可能必须先检查黑人,然后再对白人进行通行证。

编辑:新代码应如下所示:

for (int i=0 ; i<columns ; i++) {
    if (solution[i] == guess[i]) {
        test[i] = true;
        black++;
    }
}

for (int i=0 ; i<columns ; i++) {
    if (solution[i] != guess[i]) {
        for (int j=0 ; j<columns ; j++) {
            if(!test[j] && j!=i && guess[j] == solution[i]) {
                test[j] = true;
                white++;
                break;
            }
        }
    }
}

07-24 15:53