UniqueGuesser

Class UniqueGuesser has to implement setFirstGuess (all concrete classes extending an abstract class should implement the abstract method of the parent) and it can and will override the protected nextGuess method:

package packt.java9.by.example.mastermind; 

import java.util.HashSet;
import java.util.Set;

public class UniqueGuesser extends Guesser {

public UniqueGuesser(Table table) {
super(table);
}

@Override
protected void setFirstGuess() {
int i = lastGuess.length-1;
for (Color color = table.manager.firstColor();
i >= 0;
color = table.manager.nextColor(color)) {
lastGuess[i--] = color;
}
}

The setFirstGuess method selects the first guess in such a way that any possible color variations that come after the first one create the guesses one after the other if we follow the algorithm.

The aux isNotUnique method returns true if the guess contains duplicate colors. It is not interesting to see how many. If all colors are the same, or only one color appears twice, it does not matter. The guess is not unique and does not fit our guesser. This method judges that.

   private boolean isNotUnique(Color[] guess) { 
final Set<Color> alreadyPresent = new HashSet<>();
for (Color color : guess) {
if (alreadyPresent.contains(color)) {
return true;
}
alreadyPresent.add(color);
}
return false;
}

To do this, it uses a Set, and any time a new color is found in the guess array, the color is stored in the set. If the set contains the color when we find it in the array, it means that the color was already used before; the guess is not unique.

     @Override 
protected Color[] nextGuess() {
Color[] guess = super.nextGuess();
while (isNotUnique(guess)) {
guess = super.nextGuess();
}
return guess;
}

The overriding nextGuess method is simple. It asks the super nextGuess implementation to make guesses but throws away those that it does not like.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.118.12.50