2021 AP CSA FRQ 1: WordMatch

2021 FRQ #1: WordMatch

Methods and Control Structures

9 Points
Timer
25:00

Problem Description

This question involves the WordMatch class, which stores a secret string and provides methods that compare other strings to the secret. The following class declaration shows the constructor, which takes the secret string, and two methods. You will implement the two methods.

WordMatch Class

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)
    {
        secret = word;
    }

    /**
     * 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-Loss, as described in part (b)
     * Precondition: guess1 and guess2 are not the same
     */
    public String findBetterGuess(String guess1, String guess2)
    { /* to be implemented in part (b) */ }
}

Scoring Rules

The score for a guess is computed by finding the number of times the guess occurs as a substring of the secret, then multiplying by the square of the guess length.

score = (number of occurrences) × (guess.length())²

Secret Guess Occurrences Score
"mississippi" "issippi" 1 1 × 7² = 49
"mississippi" "iss" 2 2 × 3² = 18
"mississippi" "sip" 1 1 × 3² = 9
"mississippi" "mist" 0 0 × 4² = 0

Part A: scoreGuess (5 points)

Write the scoreGuess method, which returns a score for guess. The score is computed by finding the number of times guess occurs as a substring of secret and then multiplying that number by the square of the length of guess.

Occurrences may overlap. For example, if secret is "aaaa" and guess is "aa", there are 3 occurrences (positions 0, 1, and 2).

🔓 Solution
public int scoreGuess(String guess)
{
    int count = 0;
    for (int i = 0; i <= secret.length() - guess.length(); i++)
    {
        if (secret.substring(i, i + guess.length()).equals(guess))
        {
            count++;
        }
    }
    return count * guess.length() * guess.length();
}

Part B: findBetterGuess (4 points)

Write the findBetterGuess method, which returns the guess with the higher score. If the scores are tied, return the guess that comes later alphabetically.

🔓 Solution
public String findBetterGuess(String guess1, String guess2)
{
    if (scoreGuess(guess1) > scoreGuess(guess2))
        return guess1;
    if (scoreGuess(guess2) > scoreGuess(guess1))
        return guess2;
    if (guess1.compareTo(guess2) > 0)
        return guess1;
    return guess2;
}

Related Practice: Methods and Control Structures

Similar FRQs:

Study Guide:

Daily Practice:

Contact form