import java.util.Arrays; import java.util.Random; import java.util.Scanner; /** * TODO Write a summary of the role of this class in the * MasterMind program. * * @author TODO add your name here */ public class MasterMind { /** * Prompts the user for a value by displaying prompt. * Note: This method should not add a new line to the output of prompt. * * After prompting the user, the method will consume an entire * line of input while reading an int. Leading whitespace is ignored. * If the value read is between min and max * (inclusive), that value is returned. Otherwise, output * "Expected value between 0 and 10." * where 0 and 10 are the values in the min and max parameters, respectively. * Invalid input may be non-integer in which case the same error message is * displayed and the user is prompted again. * * Note: This is a general purpose method to prompt for, read and validate an int * within the min and max. This method should be tested for any min and max. * * @param input The Scanner instance to read from System.in. * @param prompt Output to the user. * @param min The minimum acceptable int value (inclusive). * @param min The maximum acceptable int value (inclusive). * @return Returns the value read from the user. */ public static int promptInt(Scanner input, String prompt, int min, int max) { return 0; //TODO replace } /** * Returns the index within arr of the first occurrence of the specified character. * If arr is null or 0 length then return -1. For all arrays, don't assume a length * but use the array .length attribute. * @param arr The array to look through. * @param ch The character to look for. * @return The index within the array of the first occurrence of the specified * character or -1 if the character is not found in the array. */ public static int indexOf(char[] arr, char ch) { return 0; //TODO replace } /** * Generates the hidden code to be guessed by the user. The hidden code * returned is an array of characters with length numPositions. * The characters in the array are randomly chosen, in order starting at index 0, * from the symbols array. * rand.nextInt( symbols.length) * is used to determine the index in the symbols array of each character * in the code. For all arrays, don't assume a length but use the array .length attribute. * * Example: * if numPositions is 3 and symbols is the array {'A','B','C'} * the returned array will have a length of 3 and may contain any selection of * the available symbols such as {'B','C','B'} or {'C','A','B'}. * * @param rand A random number generator. * @param numPositions The number of symbols in the code. * @param symbols The symbols to choose from. * @return An array of length numPositions of randomly chosen symbols. */ public static char[] generateHiddenCode(Random rand, int numPositions, char[] symbols) { return null; //TODO replace } /** * Checks whether the code is the correct length and only contains valid symbols. * Uses the indexOf method you wrote to check whether each character in the input is in the * symbols array. If code or symbols are null then false is returned. * For all arrays, don't assume a length but use the array .length attribute. * * @param numPositions The required number of symbols in the code. * @param symbols The allowed symbols in the code. * @param code The code that is being checked. * @return true if the code is the correct length and has only valid symbols otherwise * returns false. */ public static boolean isValidCode( int numPositions, char [] symbols, char [] code) { return false; //TODO replace } /** * Prompts the user for a string value by displaying prompt. * Note: This method should not add a new line to the output of prompt. * * After prompting the user, the method will read an entire line of input and remove * leading and trailing whitespace. If the line equals the single character '?' * then return null. If the line is a valid code (determine with isValidCode) return * the code, otherwise print "Invalid code." and prompt again. * * @param input The Scanner instance to read from System.in * @param prompt The user prompt. * @param numPositions The number of code positions. * @param symbols The valid symbols. * @return Returns null or a valid code. */ public static char[] promptForGuess(Scanner input, String prompt, int numPositions, char[] symbols) { return null; //TODO replace } /** * Returns the sum of "black hits" and "white hits" between the hiddenCode * and guess. A "black hit" indicates a matching symbol in the same position in the * hiddenCode and guess. A "white hit" indicates a matching symbol but different * position in the hiddenCode and guess that is not already accounted for with other * hits. * * Algorithm to determine the total number of hits: * * Count the number of each symbol in the hiddenCode, and separately count the * number of each symbol in the guess. For each symbol, determine the minimum of the * count of that symbol in the hiddenCode and the count of that symbol found in the guess. * The total number of hits, black and white, is the sum of these minimums for * all the symbols. * * Algorithm based on Donald Knuth, 1976, The Computer As Master Mind, * J. Recreational Mathematics, Vol. 9(1) * * Suggestion: To do the count, create an array of int the length of the number of symbols. * For each symbol use the indexOf method you wrote to determine the index in the array to increment * the symbols count. * * @param hiddenCode The code hidden from the user. * @param guess The user's guess of the code. * @param symbols The possible symbols in the hiddenCode and guess. * @return The total number of hits. */ public static int countAllHits(char[] hiddenCode, char[] guess, char[] symbols) { return 0; //TODO replace } /** * Returns the number of each kind of hit the guess has with the code. * The results are an array of length Config.HITS_ARRAY_LENGTH. * The count of the number of symbols in the guess that correspond in position * and symbol with the hidden code are recorded in the Config.BLACK_HITS_INDEX * position within the result array. The number of symbols that match between * the guess and the hidden code but are in different positions and not otherwise * counted are recorded in the Config.WHITE_HITS_INDEX within the result array. * * Algorithm: * Count the number of black hits - the number of positions in the guess and hidden code * that have the same symbol. * Count the total number of hits using countAllHits and subtract to find the number * of white hits. White hits are symbols that match between guess and hiddenCode that * are not in the same position and not already accounted for with other hits. * * @param hiddenCode The code the user is trying to guess. * @param guess The user's guess. * @param symbols The possible symbols in the hiddenCode and guess. * @return The array containing the number of "black hits" and "white hits". */ public static int[] determineHits(char[] hiddenCode, char[] guess, char[] symbols) { return null; //TODO replace } /** * Prints out the game board showing the guesses and the corresponding hits. * See output examples. * Game board example: * 6) [4, 5, 2, 4] BBBB * 5) [4, 4, 2, 5] BBWW * 4) [4, 4, 2, 4] BBB * 3) [1, 3, 3, 3] * 2) [2, 3, 3, 3] W * 1) [1, 1, 2, 2] B * * Only rows with non-null guesses are shown. The number on the left is the guess, * so the guesses are shown from last to first. * Looking at one line in detail: * 5) [4, 4, 2, 5] BBWW * ^^ 2 white hits, the 2nd 4 and 5 (we don't know which until solved) * ^^ 2 black hits, the 1st 4 and 2 (we don't know which until solved) * ^^^^^^^^^^^^ the guess output using Arrays.toString() * ^^ the guess number * The symbols B and W are the characters from Config.BLACK_HIT_SYMBOL and * Config.WHITE_HIT_SYMBOL. All the black hits will be shown before the white hits. * The length of all arrays should be determined using the array .length attribute, not * assumed from a constant. * * @param guesses The array of guesses. Each row is a guess or null (meaning no guess * yet). * @param hits The array of hits. Each row is the hits from determineHits for * the corresponding guess in the parallel guesses array, or null. */ public static void printBoard(char[][] guesses, int[][] hits) { } /** * The MasterMind main method that contains the welcome and the main game * loop. Carefully examine example output to help answer questions on prompts and * how this program should work. * * Algorithm: * Use appropriate constants from Config. For example, to create an array use Config.MAX_GUESSES, * but once an array exists don't use the constants but use the array .length attribute. * Determine seed or not (call promptInt with Integer.MIN_VALUE, Integer.MAX_VALUE) * Display welcome message. * Generate the hidden code (call generateHiddenCode) * Create 2D arrays for guesses and corresponding hits. Initially every row is null * until guesses are made and hits are determined for a guess. * (milestone 3) enumerate all the possibilities (call enumeratePossibilities) * Loop * Prompt for guess (call promptForGuess) * (milestone 3) If guess is null then call computerGuess * Determine how many black and white hits (call determineHits) * Output the board (call printBoard) * (milestone 3) Output number of remaining possibilities * End loop when won or lost * Output won or lost message. * * @param args unused */ public static void main(String[] args) { } /** * Determine the next code in sequence given the ordered symbols and * a code. See MasterMindTests.testNextCode() method for various test cases. * Most significant positions are the left most, just like for a number * such as 1234, where 1 is the most significant digit. * * Consider how you would add 1 to 199. Work out on paper. Now try with * the symbols A, B, C in that order. If you added B to BC what would * the result be? CA? * * Algorithm: * Loop from least significant position to the most significant * Find the index of the symbol * if least significant position * if last symbol then * set to first symbol and carry * else set next symbol * else * if carry and last symbol * set to first symbol and keep carry set * else if carry and not last symbol * set next symbol, clear carry * else * no carry, so keep symbol * end if * end if * End loop * If carry then prepend an additional symbol. Since, in decimal, leading 0's * are assumed then we assume the same for any symbols. So, we would prepend * the 2nd symbol, in decimal a 1. * * @param code A code with the symbols. * @param symbols The symbols to use for the code. * @return The next code in the sequence based on the order of the symbols. */ public static char[] nextCode(char[] code, char[] symbols) { return null; //TODO replace } /** * List all the possibilities (permutations) of codes for the specified number of * positions and the provided codes. * * Algorithm: * Create an array the length being the number of possibilities (permutations). * For example, 3 symbols in each of 4 positions means there are 3*3*3*3 or 3^4 * which equals 81 permutations. * Determine the "first" code (all positions having the same first symbol). * For each permutation call nextCode to generate the next code from the current. * * If numPositions is less than or equal to 0 or symbols is 0 length or null * then return null. * * @param numPositions The number of positions in a code. * @param symbols The possible symbols used in a code. * @return An array of all the possible codes that can be generated from the * symbols for the numPositions. */ public static char[][] enumeratePossibilities(int numPositions, char[] symbols) { return null; //TODO replace } /** * Updates the remaining possibilities array and returns the number * of possibilities. * The hiddenCodeHits parameter contains the black and white hits when the guess is compared * to the code. The possibilities parameter contains all the possible remaining candidates * for the hidden code. Determine the hits for each non-null guess when compared to each * possibility and only keep the possibilities that match the result parameter hits. * Remove a possibility from the array of possibilities by setting it to null. * * @param guess The current guess * @param hiddenCodeHits The hits when guess is compared to hiddenCode. * @param possibilities The remaining codes that contain the hidden code. * @param symbols The potential symbols in the codes. * @return The number of remaining possibilities. */ public static int updatePossibilities(char[] guess, int[] hiddenCodeHits, char[][] possibilities, char[] symbols) { return 0; //TODO replace } /** * Select the first remaining code (lowest index) from possibilities. * If no codes are left then return null. * * @param possibilities The array of remaining possible codes. * @return A code from the array. */ public static char[] computerGuess(char[][] possibilities) { return null; //TODO replace } }
Note: Comments are removed from the code because length of the code is exceeded to post the answer.
Screenshots of the code: MasterMind.java
Config.java:
Sample output:
Code to copy: MasterMind.java
import java.util.Arrays;
import java.util.Random;
import java.util.Scanner;
public class MasterMind
{
public static int promptInt(Scanner input, String
prompt, int min, int max)
{
int number;
while(true)
{
System.out.print(prompt);
//print the
prompt without newline
try
{
number=input.nextInt();
if(number<=max||number>=min)
return number;
else
throw new NumberFormatException();
}
catch(NumberFormatException e)
{
System.out.printf("Expected value between %d and
%d.\n",min,max);
continue;
}
}
}
public static int indexOf(char[] arr, char ch)
{
for(int
i=0;i<arr.length;i++)
if(arr[i]==ch)
return i;
return -1; // TODO replace
}
public static char[] generateHiddenCode(Random rand,
int numPositions, char[] symbols)
{
char[] hiddenCode = new char
[numPositions];
if ((symbols.length >=
numPositions) == true)
{
for(int i=0;
i<numPositions;i++)
hiddenCode[i] =
symbols[rand.nextInt(symbols.length)];
}
return hiddenCode;
}
public static boolean isValidCode(int numPositions,
char[] symbols, char[] code)
{
if(code==null||symbols==null||code.length!=numPositions)
return
false;
for(int
i=0;i<numPositions;i++)
{
//If invalid
symbol in the code return false
if(indexOf(symbols, code[i])==-1)
{
//System.out.println("\n"+code[i]);
return false;
}
}
/* return true if the code is the
correct length
* and has only valid
symbols*/
return true;
}
public static char[] promptForGuess(Scanner input,
String prompt,
int numPositions, char[] symbols)
{
while(true)
{
System.out.print(prompt);
String lineStr =
input.nextLine().trim();
if(lineStr.equals("?"))
{
return null;
}
else
if(isValidCode(numPositions, symbols, lineStr.toCharArray()))
{
return lineStr.toCharArray();
}
else
{
System.out.println("Invalid code.");
}
}
}
public static int countAllHits(char[] hiddenCode,
char[] guess, char[] symbols)
{
/*
* Count the number of each symbol
in the hiddenCode,
* and separately count the number
of each symbol in the guess.
*/
int hiddenCount[]=new
int[symbols.length];
int guessCount[]=new
int[symbols.length];
//Declare and initialse counter of
black and white hits
int black_hits=0;
int white_hits=0;
//check whether both are same or
not
if(guess.length==hiddenCode.length)
{
//Initialise all
values to zero
for(int
i=0;i<symbols.length;i++)
{
hiddenCount[i]=0;
guessCount[i]=0;
}
//count the
length of the each symbol
for(int
i=0;i<hiddenCode.length;i++)
{
//count the length of the each symbol in hidden
code
int indx=indexOf(symbols,hiddenCode[i]);
if(indx != -1)
{
hiddenCount[indx]++;
}
//count the length of the each symbol in
guess
indx=indexOf(symbols,guess[i]);
if(indx != -1)
{
guessCount[indx]++;
}
}
//find black and
white hits
for(int
i=0;i<guess.length;i++)
{
//find symbol index
int indx=indexOf(symbols,guess[i]);
boolean found=true;
if(guess[i]==hiddenCode[i])
{
//incremnet black hits
black_hits++;
}
else if(indexOf(hiddenCode,guess[i])!=-1
&&hiddenCount[indx]>=1)
{
/*Incremnet white hits
* Ifmatching symbol but
different
* position in the hiddenCode
and guess
*/
white_hits++;
}
else
found=false;
//if equal than decreament the counters
if(indx != -1&&found)
{
hiddenCount[indx]--;
guessCount[indx]--;
}
}
}
return black_hits+white_hits; //
TODO replace
}
public static void printBoard(char[][] guesses,
int[][] hits)
{
for(int
i=0;i<guesses.length;i++)
{
System.out.print(guesses[i]+" ");
for(int
j=0;j<hits[i][0];j++)
System.out.print(Config.BLACK_HITS_SYMBOL);
for(int
j=0;j<hits[i][1];j++)
System.out.print(Config.WHITE_HITS_SYMBOL);
System.out.println();
}
}
public static int[] determineHits(char[] hiddenCode,
char[] guess, char[] symbols)
{
int HITS_ARRAY[]=new
int[Config.HITS_ARRAY_LENGTH];
//Declare and initialse counter of
black and white hits
int black_hits=0;
for(int
i=0;i<hiddenCode.length;i++)
{
if(guess[i]==hiddenCode[i])
{
//incremnet black hits
black_hits++;
}
}
int
totalHits=countAllHits(hiddenCode,guess, symbols);
//index position 0 for black hits
and 1 for white hits
HITS_ARRAY[Config.BLACK_HITS_INDEX]=black_hits;
//to caluclate white hits
HITS_ARRAY[Config.WHITE_HITS_INDEX
]=totalHits-black_hits;
return HITS_ARRAY; // TODO
replace
}
public static void main(String[] args) {
//check whether the integer between
min and max is returned.
Scanner in = new
Scanner("8\n");
int expected = 8;
int result = MasterMind.promptInt(in, "Enter integer: ", 5,
15);
if ( expected != result) {
System.out.println("1) testPromptInt expected: " + expected + "
result: " + result);
}
else
System.out.println("testPromptInt passed");
//check whether the index of 'b' is returned
char [] list = {'a', 'A', 'b','B'};
expected = 2;
result = MasterMind.indexOf( list, 'b');
if ( expected != result) {
System.out.println("1) testIndexOf expected: " + expected + "
result: " + result);
}
else
System.out.println("testIndexOf passed");
//"randomly" chooses 3 symbols from the list
//We know which 3 will be chosen since we set the seed
Random rand = new Random(123);
int numPositions = 3;
char [] symbols = {'A', 'B', 'C', 'D'};
char [] expect = {'C', 'A', 'D'};
char [] result1 = MasterMind.generateHiddenCode( rand,
numPositions, symbols);
if ( !Arrays.equals( expect, result1)) {
System.out.println("1) testGenerateHiddenCode expected: "
+
Arrays.toString(expect)
+ " result: " +
Arrays.toString(result1));
}
else
System.out.println("testGenerateHiddenCode
passed");
//tests 6 digits, starting at 0000 and incrementing 1
{
char[] symbols1 = {'0', '1', '2', '3', '4', '5'};
char[] input3 = {'0', '0', '0', '0'};
char[] expected11 = {'0', '0', '0', '1'};
char[] result3 = MasterMind.nextCode(input3, symbols1);
if (!Arrays.equals(expected11, result3)) {
System.out.println("testNextCode 1 expected=" +
Arrays.toString(expected11)
+ " result=" + Arrays.toString(result3));
}
else
System.out.println("testNextCode passed");
}
}
public static char[] nextCode(char[] code, char[]
symbols)
{
char[] newcode=new
char[code.length];
boolean continues=true;
int
index=0;//i=code.length-1;
for(int
i=code.length-1;i>=0;i--)
{
index =
indexOf(symbols,code[i]);
if(i==code.length-1||continues)
{
if(code[i]==symbols[symbols.length-1])
{
newcode[i]=symbols[0];
}
else{
newcode[i]=symbols[index+1];
continues=false;
}
}
else
newcode[i]=code[0];
}
if(continues)
{
char
codeExtend[]=new char[code.length+1];
codeExtend[0]=symbols[1];
//copy to other
new array
for(int
i=0,j=1;i<newcode.length;i++,j++)
codeExtend[j]=newcode[i];
newcode=codeExtend;
}
return newcode; // TODO
replace
}
public static char[][] enumeratePossibilities(int
numPositions, char[] symbols)
{
int total_per =(int)
Math.pow(symbols.length, numPositions);
char array[][]=new
char[total_per][symbols.length];
for(int
i=0;i<numPositions;i++)
{
array[0][i]=symbols[0];
}
for(int
j=1;j<total_per;j++)
{
char[]
nextword=nextCode(array[j-1],symbols);
if(nextword.length>numPositions)
{
for(int i=0;i<numPositions;i++)
{
array[j][i]=nextword[i];
}
}
else
array[j]=nextword;
}
return array; // TODO replace
}
}
Config.java:
public class Config
{
static final boolean DEBUG = false;
public static final char[] CODE_SYMBOLS = new char[] {'1', '2',
'3', '4', '5', '6'};
public static final int CODE_POSITIONS = 4;
public static final int MAX_GUESSES = 10;
public static final int HITS_ARRAY_LENGTH = 2;
public static final int BLACK_HITS_INDEX = 0;
public static final int WHITE_HITS_INDEX = 1;
public static final char BLACK_HITS_SYMBOL = 'B';
public static final char WHITE_HITS_SYMBOL = 'W';
}
import java.util.Arrays; import java.util.Random; import java.util.Scanner; /** * TODO Write a summary of the role of...
/** * Returns the sum of "black hits" and "white hits" between the hiddenCode and * guess. A "black hit" indicates a matching symbol in the same position in the * hiddenCode and guess. A "white hit" indicates a matching symbol but different * position in the hiddenCode and guess that is not already accounted for with * other hits. * * Algorithm to determine the total number of hits: * ...
Here is the indexOf method that I wrote: public static int indexOf(char[] arr, char ch) { if(arr == null || arr.length == 0) { return -1; } for (int i = 0; i < arr.length; i++) { if(arr[i] == ch) { return i; } } return -1; ...
complete this in java import java.io.File; import java.io.FileNotFoundException; import java.util.ArrayList; import java.util.Random; import java.util.Scanner; public class WordDetective { /** * Picks the first unguessed word to show. * Updates the guessed array indicating the selected word is shown. * * @param wordSet The set of words. * @param guessed Whether a word has been guessed. * @return The word to show or null if all have been guessed. */ public static String pickWordToShow(ArrayList<String> wordSet, boolean []guessed) { return null; //TODO...
Can someone help me with the writing of this code please? public static int promptInt(Scanner input, String prompt, int min, int max) { return 0; //TODO replace } /** * Returns the index within arr of the first occurrence of the specified character. * If arr is null or 0 length then return -1. For all arrays, don't assume a length * but use the array .length attribute. * @param arr The array to look...
For this lab you will write a Java program that plays a simple Guess The Word game. The program will prompt the user to enter the name of a file containing a list of words. These words mustbe stored in an ArrayList, and the program will not know how many words are in the file before it starts putting them in the list. When all of the words have been read from the file, the program randomly chooses one word...
Given java code is below, please use it!
import java.util.Scanner;
public class LA2a {
/**
* Number of digits in a valid value sequence
*/
public static final int SEQ_DIGITS = 10;
/**
* Error for an invalid sequence
* (not correct number of characters
* or not made only of digits)
*/
public static final String ERR_SEQ = "Invalid
sequence";
/**
* Error for...
I need assistance with this method. Don't change the method type, decoding UTF8 import java.util.Scanner; /** * Determines if a sequence of cells of length len in a game board is clear or not. This is used * to determine if a ship will fit on a given game board. The x and y coordinates passed in as * parameters represent the top-left cell of the ship when considering the grid. * * @param board The game board to search....
package week_4; import input.InputUtils; import java.lang.reflect.Array; import java.util.ArrayList; import java.util.Random; import static input.InputUtils.positiveIntInput; import static input.InputUtils.yesNoInput; /** Write a program to roll a set of dice. Generate a random number between 1 and 6 for each dice to be rolled, and save the values in an ArrayList. Display the total of all the dice rolled. In some games, rolling the same number on all dice has a special meaning. In your program, check if all dice have the same value,...
Complete the code: package hw4; import java.io.File; import java.io.IOException; import java.util.LinkedList; import java.util.Scanner; /* * This class is used by: * 1. FindSpacing.java * 2. FindSpacingDriver.java * 3. WordGame.java * 4. WordGameDriver.java */ public class WordGameHelperClass { /* * Returns true if an only the string s * is equal to one of the strings in dict. * Assumes dict is in alphabetical order. */ public static boolean inDictionary(String [] dict, String s) { // TODO Implement using binary search...
complete this in java import java.io.File; import java.io.FileNotFoundException; import java.util.ArrayList; import java.util.Random; import java.util.Scanner; public class WordDetective { /** * Picks the first unguessed word to show. * Updates the guessed array indicating the selected word is shown. * * @param wordSet The set of words. * @param guessed Whether a word has been guessed. * @return The word to show or null if all have been guessed. */ public static String pickWordToShow(ArrayList<String> wordSet, boolean []guessed) { return null;...