Source Code Listing 3
- By Vince Huston
- February 24, 2001
Component JAVA
Mastermind and Design Paradigms
Vince Huston
Listing 3.
import java.io.*;
public class MastermindPlayDS2 {
public static void main( String[] args ) throws IOException {
BufferedReader rdr = new BufferedReader( new InputStreamReader( System.in ));
String str = null;
BoardDS2 board = new BoardDS2();
int[] response = new int[2];
while (response[0] != BoardDS2.NUM_SLOTS) {
System.out.print( "Enter guess: " );
str = rdr.readLine();
board.evaluate( str.toCharArray(), response );
System.out.println( " " + response[0] + ' ' + response[1] );
} } }
class BoardDS2 {
public static final int NUM_CHOICES = 6;
public static final int NUM_SLOTS = 4;
private char[] answer = new char[NUM_SLOTS];
private int[] answerChars = new int[NUM_CHOICES];
private int[] guessChars = new int[NUM_CHOICES];
public BoardDS2() {
// populate answer array with random characters
for (int i=0; i < num_slots;="" i++)="" answer[i]="(char)" ('a'="" +="" (int)="" (math.random()*1000)="" %="" num_choices);="" initialize="" the="" answer="" count="" array="" for="" (int="" i="0;" i="">< num_slots;="" i++)="" answerchars[="" answer[i]="" -="" 'a'="" ]++;="" }="" public="" void="" evaluate(="" char[]="" guess,="" int[]="" response="" )="" {="" response[0]="response[1]" =="" 0;="" initialize="" the="" guess="" count="" array="" for="" (int="" i="0;" i="">< num_choices;="" i++)="" guesschars[i]="0;" for="" (int="" i="0;" i="">< num_slots;="" i++)="" guesschars[="" guess[i]="" -="" 'a'="" ]++;="" compute="" black="" answer="" for="" (int="" i="0;" i="">< num_slots;="" i++)="" if="" (guess[i]="=" answer[i])="" response[0]++;="" over-compute="" white="" answer="" for="" (int="" i="0;" i="">< num_choices;="" i++)="" response[1]="" +="Math.min(" guesschars[i],="" answerchars[i]="" );="" eliminate="" the="" overlap="" response[1]="response[1]" -="" response[0];="" }="" }="">