Class DonaldKnuthAlgorithm


public class DonaldKnuthAlgorithm extends MastermindAlgorithm
An implementation of the Donald Knuth algorithm for solving the Mastermind game.
  • Constructor Details

    • DonaldKnuthAlgorithm

      public DonaldKnuthAlgorithm()
      Constructs a new instance of the `DonaldKnuthAlgorithm` class.

      This constructor initializes the algorithm by generating all possible permutations of the secret code, as required by Donald Knuth's Mastermind solving algorithm.

  • Method Details

    • guess

      public Code guess()
      Determines the initial guess for the Mastermind game.
      Specified by:
      guess in class MastermindAlgorithm
      Returns:
      The initial guess to be made by the algorithm.
      Throws:
      IllegalCallerException - If this method is invoked for subsequent guesses.
    • guess

      public Tuple2<Status,Code> guess(Response response) throws InvalidHintsException
      Produces the next guess in the Mastermind game based on the feedback from the previous guess.

      This method is only intended for subsequent guesses after the initial guess. It evaluates the feedback provided in the form of a Response object, determines the current game status, and updates the state of the algorithm.

      The algorithm executes the following steps:
      1. Checks if the method is being called correctly for subsequent guesses. Throws an IllegalCallerException if called for the initial guess.
      2. Retrieves the validation counts (e.g., correct positions) from the response.
      3. If the number of correct positions equals the secret code length (Mastermind.CODE_LENGTH), declares the player as a winner by returning a Tuple2 containing status Status.Win and the last guess.
      4. If the maximum allowable guesses are exceeded and no match is found, declares the player as a loser by returning a Tuple2 containing status Status.Lose and the last guess.
      5. Filters out invalid permutations that do not align with the response feedback using the reducePermutations method.
      6. Finds the next optimized guess using the findNextGuess method.
      7. Updates the last guess with the next guess and returns a Tuple2 containing status Status.Continue and the next guess.

      Specified by:
      guess in class MastermindAlgorithm
      Parameters:
      response - The feedback received for the previous guess, containing the number of correct positions and other match details.
      Returns:
      A Tuple2<Status, Code> object where Status represents the current game status (e.g., Win, Lose, Continue), and Code represents the next guess to be made.
      Throws:
      IllegalCallerException - If this method is invoked for the initial guess.
      InvalidHintsException - If the algorithm encounters an invalid hint during the process.