FRQ Question 1

The FRQ AP CSA 2021 Exam had question 1 asking to create a word guessing game. This involves making the WordMatch class with a secret string. Our job was to create two methods in said class to finish the entire code amount of frq in 2021.

Question 1 part a

The first method we have to create is scoreGuess. This will show what score is returned by seeing the number of times the guess is part of the secret substring. It is then multiplied by the square of the length of the guess.

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());
}

Question 1 part b

The second method that needs to be created is the findBetterGuess method which will return the better guess between two guesses that are inputted into the method. The guess that has a higher score will be returned.

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

This is the final result of the code as an entire whole.

public class WordMatch {
    private String secret;
  
    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());
      }
    }
    
    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;
      }
    }