FRQ 2021
1)
a. Write the WordMatch
method scoreGuess
. To determine the score the returned, scoreGuess
finds the number of times that guess
occurs as a substring of secret
and then multiplies that number by the square of the length of guess
. Occurrences of guess
may overlap within secret
.
b. Write the WordMatch
method findBetterGuess
, which returns the better guess
of its two String
parameters, guess1
and guess2
. If the scoreGuess
method returns different values for guess1
and guess2m
then the guess with the higher score is returned. If the scoreGuess
method returns the same value for guess1
and guess2
, then the alphabetically greater guess is returned.
/**
* Main class for WordMatch.java
*
*/
public class WordMatch
{
private String secret;
public WordMatch(String secret)
{
this.secret = secret;
}
/**
* scoreGuess
*
* @param guess
* @return
*/
public int scoreGuess(String guess)
{
int lastIndex = 0;
int count = 0;
while (lastIndex != -1) {
lastIndex = secret.indexOf(guess, lastIndex);
if (lastIndex != -1) {
count++;
lastIndex += guess.length();
}
}
return count * guess.length() * guess.length();
}
public String findBetterGuess(String guess1, String guess2)
{
int guessA = scoreGuess(guess1);
int guessB = scoreGuess(guess2);
if(guessA > guessB) return guess1;
if(guessB > guessA) return guess2;
if((guess1.compareTo(guess2)) > 0)
{
return guess1;
}
return guess2;
}
public static void main (String[] Args)
{
}
}
WordMatch game = new WordMatch("mississippi");
int play = game.scoreGuess("mississippi");
System.out.printf("Guess: mississippi\nScore: %d\n", play);
WordMatch game2 = new WordMatch("concatenation");
int play2 = game2.scoreGuess("nation");
System.out.printf("\nGuess 1: ten\nScore: %d\n", play2);
System.out.printf("\nGuess 2: nation\nScore: %d\n", play2);