Unit 2 HW
Jupyter Notebook on unit 2 hw
public class WordMatch
{
/** The secret string. */
private String secret;
/** Constructs a WordMatch object with the given secret string of lowercase letters. */
public WordMatch(String word)
{
/* implementation not shown */
}
/** Returns a score for guess, as described in part (a).
* Precondition: 0 < guess.length() <= secret.length()
*/
public int scoreGuess(String guess)
{ /* to be implemented in part (a) */ }
/** Returns the better of two guesses, as determined by scoreGuess and the rules for a
* tie-breaker that are described in part (b).
* Precondition: guess1 and guess2 contain all lowercase letters.
* guess1 is not the same as guess2.
*/
public String findBetterGuess(String guess1, String guess2)
{ /* to be implemented in part (b) */ }
}
public class WordMatch
{
/** The secret string. */
private String secret;
/** Constructs a WordMatch object with the given secret string of lowercase letters. */
public WordMatch(String word)
{
this.secret = word;
}
/** Returns a score for guess, as described in part (a).
* Precondition: 0 < guess.length() <= secret.length()
*/
public int scoreGuess(String guess)
{
int times = 0;
// initializes the occurences
for(int i = 0; i < secret.length(); i++) {
// for as long as i is not greater than the length of the secret word, it will iterate
int x = i + guess.length();
// x is the end length of the guess
if(x <= secret.length() && secret.substring(i, x).equals(guess))
// if x is shorter than the the secret of the word, then it will keep going
times++;
// increments if the guess matches the substring secret
}
return times * (guess.length() * guess.length());
}
/** Returns the better of two guesses, as determined by scoreGuess and the rules for a
* tie-breaker that are described in part (b).
* Precondition: guess1 and guess2 contain all lowercase letters.
* guess1 is not the same as guess2.
*/
public String findBetterGuess(String guess1, String guess2) {
int score1 = scoreGuess(guess1);
// each of the guesses are put into the method before it to yield two integers
int score2 = scoreGuess(guess2);
//compares the ints using conditionals to return the word with a greater value
if(score1 > score2)
return guess1;
else if(score2 > score1)
return guess2;
else {
// returns the guess that is a longer amount of characters if they are the same
if(guess1.compareTo(guess2) > 0)
return guess1;
else
return guess2;
}
}
public static void main(String[] args) {
WordMatch testA = new WordMatch("mississippi");
System.out.println(testA.scoreGuess("is"));
System.out.println(testA.scoreGuess("mississippi"));
WordMatch testB = new WordMatch("concatenation");
System.out.println(testB.findBetterGuess("ten" , "nation"));
System.out.println(testB.findBetterGuess("con", "cat"));
}
}
WordMatch.main(null)