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 (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
- CombinedTable Free Response Solution
- ClubMembers Free Response Solution
- ArrayResizer Free Response Solution
Help & comments
Get help from AP CS Tutor Brandon Horn