2021 FRQ 1

1)
a)
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) {
        int score = 0;
        for (int i = 0; i < secret.length()-guess.length(); i++) {
            if (secret.substring(i + guess.length()).equals(guess)) {
                score++;
            }
        }
        return score * guess.length() * guess.length();
    }
    public String findBetterGuess (String guess1, String guess2) {
        // part b
    }
}

Comments

I had to google how to do substring in java but that was the only hard 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) {
        /* implementation not shown */
    }
    /** Returns a score for guess, as described in part (a).
    * Precondition: 0 < guess.length() <= secret.length()
    */
    public int scoreGuess (String guess) {
        // part a
    }
    public String findBetterGuess (String guess1, String guess2) {
        if (scoreGuess(guess1) > scoreGuess(guess2)) {
            return guess1;
        } else if (scoreGuess(guess1) < scoreGuess(guess2)) {
            return guess2;
        } else if (guess1.compareTo(guess2) > 0) {
            return guess1;
        }
    }
}

Comments

The first two ifs were very simple but the alphabetical condition was a little more difficult. I didn't know how to compare effectively in Java and I had to google, find out about the compareTo() function, then learn what it does.