实现Knuths Mastermind算法Java

时间:2013-11-01 22:42:51

标签: java algorithm knuth

我正在尝试在java中实现Knuths Mastermind算法。该算法在本文中进行了解释,paper。到目前为止,这是我实现它的方式,但它需要的时间超过算法应该采取的最多5次猜测。

    private static void makeGuess() {
    attempts++;
    /*Secret is the code that we are trying to guess, posGuess is a list of
     *  all possible guesses and guesses is a list of all remaining guesses*/
    if(attempts == 1){/*if first guess, guess BBGG*/
        currentGuess = "BBGG";
    }else{
    for (int i = 0; i < guesses.size(); i++) { /*Remove all guesses with a score that isn't the same as the current score*/
        if (getScore(currentGuess, secret) != getScore(currentGuess,
                    guesses.get(i))) {
                guesses.remove(currentGuess);
                guesses.remove(i);
            }
    }
    if(guesses.size() == 1){ /*If one guess is remaining then make this the new guess*/
        currentGuess = guesses.get(0);
    }else{
    /*
     * For each guess scored against each other guess find the score and the score array. 1 white marker gives score of 1, 1 black gives score of 2, etc. 
     * Then if the maximum of the current score list is greater than previous maximums set new max and set current guess
     */
    for (int i = 0; i < posGuesses.size(); i++) {
        int scores[] = {0,0,0,0,0,0,0,0,0,0,0,0,0,0};
        for (int j = 0; j < guesses.size(); j++) {
            scores[getScore(posGuesses.get(i), guesses.get(j))] ++;
        }
            if(getMax(scores,scores.length) < max){
                max = getMax(scores,scores.length);
                System.out.println("Max: " + max);
                currentGuess = guesses.get(i);
            }
    }
    }
    }
    guesses.remove(currentGuess);

}

假设其他方法,例如评分方法和getMax方法,按预期工作,为什么这不起作用?

0 个答案:

没有答案