WordMatch is #1 from the from the 2021 AP Computer Science A Free Response problems.

https://apcentral.collegeboard.org/pdf/ap21-frq-computer-science-a.pdf?course=ap-computer-science-a

Part (a) scoreGuess method

public int scoreGuess(String guess)
{
    int count = 0;

    for(int i = 0; i < secret.length(); i++)
    {
        int j = i + guess.length();

        if(j <= secret.length() && secret.substring(i, j).equals(guess))
            count++;
    }

    return count * (guess.length() * guess.length());
}

I would normally have used indexOf for this problem; however, the description mentioned that the occurrences of guess might overlap (and the second example showed such a situation). This approach seemed more reliable to me.

See more about manipulating Strings on the AP CS A Exam.

Part (a) scoreGuess method (alternate)

public int scoreGuess(String guess)
{
    int count = 0;
    String secretLeft = secret;
    int guessIndex = secretLeft.indexOf(guess);

    while(guessIndex >= 0)
    {
        count++;
        secretLeft = secretLeft.substring(guessIndex + 1);
        guessIndex = secretLeft.indexOf(guess);
    }

    return count * (guess.length() * guess.length());
}

This approach uses indexOf to find the next occurrence of guess in secretLeft, or determine that no such occurrence exists.

secretLeft = secretLeft.substring(guessIndex + 1); removes the characters before and including guessIndex (the first letter of guess). Removing the entire guess would prevent counting overlapping occurrences.

Part (b) findBetterGuess method

public String findBetterGuess(String guess1, String guess2)
{
    int score1 = scoreGuess(guess1);
    int score2 = scoreGuess(guess2);

    if(score1 > score2)
        return guess1;
    else if(score2 > score1)
        return guess2;
    else
    {
        if(guess1.compareTo(guess2) > 0)
            return guess1;
        else
            return guess2;
    }
}

See compareTo on the AP CS A Exam.

2021 AP CS Exam Free Response Solutions

Help & comments

Get help from AP CS Tutor Brandon Horn

Comment on WordMatch