# WordMatch free response2

WordMatch free response problem from the 2021 AP Computer Science A Exam.

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.

## 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;
}
}
```

## 2 thoughts on “WordMatch free response”

1. Dhruv Kaushik

For part a, it is not required to check if guess’s length is equal to secret’s length?

• Brandon Horn

The precondition specified that `guess.length()` was at least 1 and no longer than `secret.length()`. You are still required to ensure that you don’t go out of bounds.