0% found this document useful (0 votes)
502 views133 pages

APCSAUnit 4 FRQs

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
502 views133 pages

APCSAUnit 4 FRQs

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 133

AP COMPUTER SCIENCE A Scoring Guide

Unit 4 FRQ

1. Directions: SHOW ALL YOUR WORK. REMEMBER THAT PROGRAM SEGMENTS ARE TO BE
WRITTEN IN JAVA.

Notes:

• Assume that the classes listed in the Java Quick Reference have been imported where appropriate.
• Unless otherwise noted in the question, assume that parameters in method calls are not null and
that methods are called only when their preconditions are satisfied.
• In writing solutions for each question, you may use any of the accessible methods that are listed in
classes defined in that question. Writing significant amounts of code that can be replaced by a call to
one of these methods will not receive full credit.

2. This question involves analyzing integer values that are obtained using the getInt method in the following
IntegerAnalysis class. You will write one method in the class.

public class IntegerAnalysis


{
/** Returns an int from simulated user input */
public static int getInt()
{ /* implementation not shown */ }

/** Analyzes n values obtained from the getInt method and returns the
proportion
* of these values that meet the criteria described in part (a)
* Precondition
Precondition: max > 0, n > 0
*/
public static double analyzeInts(int max, int n)
{ /* to be implemented in part (a) */ }

// There may be variables and methods that are not shown.


}

(a) Write method analyzeInts, which obtains n values using the getInt method and returns the
proportion of the obtained values that meet all the following criteria.

• The value is greater than 0


• The value is less than max
• The value is divisible by 3

For example, if max is 10 and the values obtained by getInt are 6, -3, 5, 0, 12, 3, 3, and 9,
then analyzeInts should return 0.5 because four of the eight values (6, 3, 3, and 9) meet all the
criteria.

Complete method analyzeInts.

AP Computer Science A Page 1 of 133


Scoring Guide

Unit 4 FRQ

/** Analyzes n values obtained from the getInt method and returns the
proportion of
* these values that meet the criteria described in part (a)
* Precondition
Precondition: max > 0, n > 0
*/
public static double analyzeInts(int max, int n)

(b) A programmer wants to modify the IntegerAnalysis class so that in the analyzeInts method, the
check for divisibility by an integer can vary between method calls. For example, in one call to
analyzeInts, the method might check for divisibility by 3, and in another call to analyzeInts, the
method might check for divisibility by 10. The programmer wants to implement this change without making
any changes to the signature of the analyzeInts method or overloading analyzeInts.

Write a description of how you would change the IntegerAnalysis class in order to support this
modification. Do not write the program code for this change.

Make sure to include the following in your response.

• Identify any new or modified variables or methods.


• Describe, for each new or revised variable or method, how it would change or be implemented,
including visibility and type.

Part A – analyzeInts

Select a point value to view scoring criteria, solutions, and/or examples and to score the response. +1 indicates a point
earned and -1 indicates a general or question-specific penalty.

+1 [Skill 3.C] Iterates times

Responses can still earn the point even if they inappropriately return inside the loop

+1 [Skill 3.A] Calls

Responses will not earn the point if they call incorrectly

+1 [Skill 3.C] Accumulates a count based on a value returned by

Responses can still earn the point even if they:

· use incorrect logic to guard the update

· do not use a loop

Responses will not earn the point if they:

· do not initialize count

· do not use a value returned by to determine update

· use multiple calls to to obtain a value for comparison

Page 2 of 133 AP Computer Science A


Scoring Guide

Unit 4 FRQ

+1 [Skill 3.C] Identifies values to include in the count based on criteria and parameters

Responses can still earn the point even if they identify values to include that are not returned by or are returned by
an incorrect call to

+1 [Skill 3.C] Returns proportion as a

Responses can still earn the point even if they accumulate count incorrectly

Responses will not earn the point if they calculate the proportion incorrectly based on count and

-1 (w) Extraneous code that causes side-effect (e.g., printing to output, incorrect precondition check)

-1 (x) Local variables used but none declared

Canonical Solution:

0 && num

0 1 2 3 4 5

Total number of points earned (minus penalties) is equal to 5.

+1 Iterates times (Points earned)


+1 Calls (Points earned)
+1 Accumulates a count based on a value returned by (Points earned)
+1 Identifies values to include in the count based on criteria and parameters (Points earned)
+1 Returns proportion as a (Points earned)
-1 [penalty] (w) Extraneous code that causes side-effect (e.g., printing to output, incorrect precondition
check) (General penalties)
-1 [penalty] (x) Local variables used but none declared (General penalties)

AP Computer Science A Page 3 of 133


Scoring Guide

Unit 4 FRQ

Canonical Solution:

0 && num < max && (num % 3 == 0)) Line 8: { Line 9: count++; Line 10: } Line 11: } Line 12: return count / n; Line
13: } end code">

Part B – variable to store divisibility criteria

Select a point value to view scoring criteria, solutions, and/or examples and to score the response. +1 indicates a point
earned and -1 indicates a general or question-specific penalty.

+1 [Skill 3.B] The response identifies properties of the new variable:

· or "integer"

· not local to a method

Responses can still earn the point even if they:

o specify the variable as an instance variable

o describe a local variable that is assigned a value only once during the method call, where the value is generated
randomly or from user input

Responses will not earn the point if they describe a change to the method header

+1 [Skill 3.B] The response describes how the method changes:

· method would need to change so that instead of checking for divisibility by 3 using %3, it would use the
new variable

Responses can still earn the point even if they describe a change to the header

Responses only earn the point if all described components are plausible, accurate, and consistent as related to the problem

0 1 2

Page 4 of 133 AP Computer Science A


Scoring Guide

Unit 4 FRQ

Total number of points earned (minus penalties) is equal to 2.

+1 The response identifies properties of the new variable (Points earned):


o or "integer"
o not local to a method
+1 The response describes how the method changes (Points earned):
o method would need to change so that instead of checking for divisibility by 3 using %3,
it would use the new variable

AP Computer Science A Page 5 of 133


Scoring Guide

Unit 4 FRQ

2. Directions: SHOW ALL YOUR WORK. REMEMBER THAT PROGRAM SEGMENTS ARE TO BE
WRITTEN IN JAVA.

Notes:

• Assume that the classes listed in the Java Quick Reference have been imported where appropriate.
• Unless otherwise noted in the question, assume that parameters in method calls are not null and
that methods are called only when their preconditions are satisfied.
• In writing solutions for each question, you may use any of the accessible methods that are listed in
classes defined in that question. Writing significant amounts of code that can be replaced by a call to
one of these methods will not receive full credit.

2. This question involves adding apples to a bag until the weight of the bag is within a specified range. The weight
of each apple is obtained using the getApple method in the following AppleBagger class. You will write
one method in the class.

public class AppleBagger


{
/** Returns the weight of the next apple to be added to the bag, with a
different weight
* being returned with each call
*/
public static double getApple()
{ /* implementation not shown */ }

/** Returns the number of apples that are added to a bag, as described
in part (a)
* Precondition
Precondition: 0 < allowedVariation < targetWeight
*/
public static int bagApples(double targetWeight,
double allowedVariation)
{ /* to be implemented in part (a) */ }

// There may be variables and methods that are not shown.


}

(a) Write the method bagApples, which obtains the weights of apples to be added to a bag using calls to the
getApple method and returns the number of apples that are added to the bag until the combined weight exceeds
targetWeight minus allowedVariation.

For example, if targetWeight is 10.0 and allowedVariation is 0.5, the bagApples method
will return the number of apples that are added until the combined weight of the apples exceeds 9.5.

Complete method bagApples.

Page 6 of 133 AP Computer Science A


Scoring Guide

Unit 4 FRQ

/** Returns the number of apples that are added to a bag, as described in
part (a)
* Precondition
Precondition: 0 < allowedVariation < targetWeight
*/
public static int bagApples(double targetWeight,
double allowedVariation)

(b) A programmer wants to modify the AppleBagger class so that the allowed variation in the bagApples
method is always equal to percent of the weight of the first apple added to the bag during a call to
bagApples, rather than a parameter passed to the method.

Write a description of how you would change the AppleBagger class in order to support this modification. Do
not write the program code for this change.

Make sure to include the following in your response.

• Identify any new or modified variables or methods.


• Describe, for each new or revised variable or method, how it would change or be implemented,
including visibility and type.

Part A – bagApples

Select a point value to view scoring criteria, solutions, and/or examples and to score the response. +1 indicates a point
earned and -1 indicates a general or question-specific penalty.

+1 [Skill 3.C] Iterates until total weight exceeds goal

Responses can still earn the point even if they:

· calculate total weight incorrectly

· calculate goal incorrectly, as long as or is used in loop test

· return early inside the loop

· confuse with

Responses will not earn the point if they use the incorrect direction for the comparison

+1 [Skill 3.A] Calls

Responses can still earn the point even if they:

· do not use or store the call’s return value

· call the method a second time incorrectly

Responses will not earn the point if they call incorrectly

+1 [Skill 3.C] Compares total weight to minus

AP Computer Science A Page 7 of 133


Scoring Guide

Unit 4 FRQ

Responses can still earn the point even if they:

· calculate total weight incorrectly

· use incorrect direction for the comparison

Responses will not earn the point if they:

· use or in comparison

· do not modify total weight within the loop

+1 [Skill 3.C] Maintains total weight of apples added so far (in the context of a loop)

Responses can still earn the point even if they:

· call incorrectly

· terminate the loop under incorrect conditions

· omit or double-count some calls to

Responses will not earn the point if they:

· do not initialize or increment total weight

· do not calculate the total weight of all values returned by correctly

+1 [Skill 3.C] Accumulates and returns count

Responses can still earn the point even if they:

· calculate total weight incorrectly

· have no loop or terminate the loop under incorrect conditions

Responses will not earn the point if they:

· do not initialize or increment count

· omit or double-count some calls to

-1 (w) Extraneous code that causes side-effect (e.g., printing to output, incorrect precondition check)

-1 (x) Local variables used but none declared

-1 (t) Do not initialize both counter and total weight

Canonical Solution:

Page 8 of 133 AP Computer Science A


Scoring Guide

Unit 4 FRQ

0 1 2 3 4 5

Total number of points earned (minus penalties) is equal to 5.

+1 Iterates until total weight exceeds goal (Points earned)


+1 Calls (Points earned)
+1 Compares total weight to minus (Points earned)
+1 Maintains total weight of apples added so far (in the context of a loop) (Points earned)
+1 Accumulates and returns count (Points earned)
-1 [penalty] (w) Extraneous code that causes side-effect (e.g., printing to output, incorrect precondition
check) (General penalties)
-1 [penalty] (x) Local variables used but none declared (General penalties)
-1 [penalty] (t) Do not initialize both counter and total weight (General penalties)

Canonical Solution:

AP Computer Science A Page 9 of 133


Scoring Guide

Unit 4 FRQ

Part B – remove allowedVariation

Select a point value to view scoring criteria, solutions, and/or examples and to score the response. +1 indicates a point
earned and -1 indicates a general or question-specific penalty.

+1 [Skill 3.B] The response identifies changes to the method header:

· parameter is removed

+1 [Skill 3.C] The response describes how the method changes:

· after retrieving the first apple, a variable would be set based on that weight, and this variable would be used in the loop
test in place of the removed parameter

Responses can still earn the point even if they do not specify a change to the method header

Responses only earn the point if all described components are plausible, accurate, and consistent as related to the problem

0 1 2

Total number of points earned (minus penalties) is equal to 2.

+1 The response identifies changes to the method header (Points earned):


o parameter is removed
+1 The response describes how the method changes (Points earned):
o after retrieving the first apple, a variable would be set based on that weight, and this variable would be
used in the loop test in place of the removed parameter

Page 10 of 133 AP Computer Science A


Scoring Guide

Unit 4 FRQ

3. Directions: SHOW ALL YOUR WORK. REMEMBER THAT PROGRAM SEGMENTS ARE TO BE
WRITTEN IN JAVA.

Notes:

• Assume that the classes listed in the Java Quick Reference have been imported where appropriate.
• Unless otherwise noted in the question, assume that parameters in method calls are not null and
that methods are called only when their preconditions are satisfied.
• In writing solutions for each question, you may use any of the accessible methods that are listed in
classes defined in that question. Writing significant amounts of code that can be replaced by a call to
one of these methods will not receive full credit.

4. This question involves analyzing a salesperson’s sales. Sales amounts are obtained using the getSales
method in the following SalesSimulator class. You will write one method in the class.

public class SalesSimulator


{
/** Simulates and returns the sales, in dollars, made by a salesperson
on a particular
* day
*/
public static int getSales()
{ /* implementation not shown */ }

/** Analyzes sales for numDays days obtained from the getSales method
and
* returns the total bonus earned by the salesperson, in dollars, as
described in part (a)
* Precondition
Precondition: goal > 0, numDays > 0
*/
public static int calculateBonus(int goal, int numDays)
{ /* to be implemented in part (a) */ }

// There may be variables and methods that are not shown.


}

(a) Write the SalesSimulator method calculateBonus, which obtains the daily sales of a salesperson
and applies a bonus based on how close to meeting or exceeding the daily sales goal the salesperson came. It
obtains daily sales for numDays days using the getSales method. For each day, if the daily sales are at
least percent of goal but less than goal, the salesperson receives a bonus. The salesperson receives a
bonus if the daily sales are greater than or equal to goal. Method calculateBonus returns the total
bonus received, in dollars, over all days.

The following table shows the bonuses received as a result of the method call

AP Computer Science A Page 11 of 133


Scoring Guide

Unit 4 FRQ

SalesSimulator.calculateBonus(200, 3).

getSales()
Daily
Day Explanation
Bonus
Return Value

Because is greater than or equal to percent of the goal


180 50 ( ) but is less than the goal, the salesperson earns a
bonus.
Because is less than percent of the goal ( ), the
150 0
salesperson earns no bonus.
Because is greater than or equal to the goal, the
200 75
salesperson earns a bonus.

For the sales shown in the table above, SalesSimulator.calculateBonus(200, 3) should return the
total bonus 125.

Complete method calculateBonus.

/** Analyzes sales for numDays days obtained from the getSales method and
returns
* the total bonus earned by the salesperson, in dollars, as described
in part (a)
* Precondition
Precondition: goal > 0, numDays > 0
*/
public static int calculateBonus(int goal, int numDays)

(b) A programmer wants to modify the SalesSimulator class so that the daily goal is maintained in a
variable with a value that cannot be changed once it is initialized.

Write a description of how you would change the SalesSimulator class in order to support this
modification. Do not write the program code for this change.

Make sure to include the following in your response.

• Identify any new or modified variables or methods.


• Describe, for each new or revised variable or method, how it would change or be implemented,
including visibility and type.

Part A – calculateBonus

Select a point value to view scoring criteria, solutions, and/or examples and to score the response. +1 indicates a point
earned and -1 indicates a general or question-specific penalty.

Page 12 of 133 AP Computer Science A


Scoring Guide

Unit 4 FRQ

+1 [Skill 3.C] Iterates times

Responses can still earn the point even if they return early inside the loop

+1 [Skill 3.A] Calls

Responses will not earn the point if they call incorrectly

+1 [Skill 3.C] Compares return value with to determine bonus categories

Responses will not earn the point if they:

· do not change bonus based on the selected category

· classify a sales amount into the wrong category, or into both categories

· call more than one time to make condition comparisons

+1 [Skill 3.C] Declares, initializes, and increments bonus appropriately in all cases (algorithm)

Responses can still earn the point even if they classify a sales amount into the wrong category, or into both categories

Responses will not earn the point if they:

· do not include a loop

· return early inside the loop

+1 [Skill 3.A] Returns identified bonus

Responses can still earn the point even if they determine bonus incorrectly

-1 (w) Extraneous code that causes side-effect (e.g., printing to output, incorrect precondition check)

-1 (x) Local variables used but none declared

Canonical Solution:

AP Computer Science A Page 13 of 133


Scoring Guide

Unit 4 FRQ

= goal) Line 8: { Line 9: bonus += 75; Line 10: } Line 11: else if (sales >= 0.8 * goal) Line 12: { Line 13: bonus += 50;
Line 14: } Line 15 is blank. Line 16: } Line 17: return bonus; Line 18: } end code">

0 1 2 3 4 5

Total number of points earned (minus penalties) is equal to 5.

+1 Iterates times (Points earned)


+1 Calls (Points earned)
+1 Compares return value with to determine bonus categories (Points earned)
+1 Declares, initializes, and increments bonus appropriately in all cases (algorithm) (Points earned)
+1 Returns identified bonus (Points earned)
-1 [penalty] (w) Extraneous code that causes side-effect (e.g., printing to output, incorrect precondition
check) (General penalties)
-1 [penalty] (x) Local variables used but none declared (General penalties)

Canonical Solution:

Page 14 of 133 AP Computer Science A


Scoring Guide

Unit 4 FRQ

= goal) Line 8: { Line 9: bonus += 75; Line 10: } Line 11: else if (sales >= 0.8 * goal) Line 12: { Line 13: bonus += 50;
Line 14: } Line 15 is blank. Line 16: } Line 17: return bonus; Line 18: } end code">

Part B – daily goal as constant

Select a point value to view scoring criteria, solutions, and/or examples and to score the response. +1 indicates a point
earned and -1 indicates a general or question-specific penalty.

+1 [Skill 3.B] The response identifies properties of the new variable:

· or "integer"

· or "constant"

+1 [Skill 3.B] The response describes how the method changes:

· method would need to change so that it only has a single parameter and would use the
variable to determine if the goal was met

Responses can still earn the point even if they omit

Responses only earn the point if all described components are plausible, accurate, and consistent as related to the problem

0 1 2

Total number of points earned (minus penalties) is equal to 2.

+1 The response identifies properties of the new variable (Points earned):


o or "integer"
o or "constant"

AP Computer Science A Page 15 of 133


Scoring Guide

Unit 4 FRQ

+1 The response describes how the method changes (Points earned):


o method would need to change so that it only has a single parameter and
would use the variable to determine if the goal was met

Page 16 of 133 AP Computer Science A


Scoring Guide

Unit 4 FRQ

4. Directions: SHOW ALL YOUR WORK. REMEMBER THAT PROGRAM SEGMENTS ARE TO BE
WRITTEN IN JAVA.

Notes:

• Assume that the classes listed in the Java Quick Reference have been imported where appropriate.
• Unless otherwise noted in the question, assume that parameters in method calls are not null and
that methods are called only when their preconditions are satisfied.
• In writing solutions for each question, you may use any of the accessible methods that are listed in
classes defined in that question. Writing significant amounts of code that can be replaced by a call to
one of these methods will not receive full credit.

2. This question involves manipulating strings that are made up of uppercase letters. The Puzzle class contains
methods used to modify keys. You will write one method in this class. A partial declaration of the Puzzle class
is shown below.

public class Puzzle


{
/** Returns a String based on a key and a letter, as described in part
(a)
* Precondition
Precondition: letter consists of one uppercase letter.
* key has at least letters and all letters are
uppercase and unique.
*/
public static String changeKey(String letter, String key)
{ /* to be implemented in part (a) */ }

// There may be variables and methods that are not shown.


}

(a) Write the Puzzle method changeKey, which uses the parameter letter to return a string based on
the parameter key. The parameter letter contains a single uppercase letter. The parameter key has at
least two letters and all letters in key are uppercase and unique. A sample key is "ABC".

The following describes the string that should be returned by the method.

If the letter is contained in the key, the method should return a new string containing all letters in the key
except letter, in their original order.
If the letter does not appear in the key, the method should return the letter.

The following table shows the results of several calls to changeKey.

AP Computer Science A Page 17 of 133


Scoring Guide

Unit 4 FRQ

Method Call Return Value


Puzzle.changeKey("G", "GXAD") "XAD"
Puzzle.changeKey("D", "GXAD") "GXA"
Puzzle.changeKey("A", "GXAD") "GXD"
Puzzle.changeKey("M", "GXAD") "M"

Complete method changeKey.

/** Returns a String based on a key and a letter, as described in part


(a)
* Precondition
Precondition: letter consists of one uppercase letter.
* key has at least letters and all letters are
uppercase and unique.
*/
public static String changeKey(String letter, String key)

(b) The programmer would like to modify the Puzzle class to keep track of how many times a call to
changeKey results in a change to a key. Any time a call to changeKey results in a change to the key, the
count of key modifications should be increased by one. The programmer would like to implement this change
without making any changes to the signature of the changeKey method or overloading changeKey.

Write a description of how you would change the Puzzle class in order to support this modification. Do not
write the program code for this change.

Make sure to include the following in your response.

• Identify any new or modified variables or methods.


• Describe, for each new or revised variable or method, how it would change or be implemented,
including visibility and type.

Part A – changeKey

Select a point value to view scoring criteria, solutions, and/or examples and to score the response. +1 indicates a point
earned and -1 indicates a general or question-specific penalty.

+1 [Skill 3.A] Locates in

Responses will not earn the point if they:

· call incorrectly or use array or syntax to access characters

· are off by one when using a loop to access characters

+1 [Skill 3.C] Returns if is not in

Responses can still earn the point even if they incorrectly determine whether letter is in

Page 18 of 133 AP Computer Science A


Scoring Guide

Unit 4 FRQ

+1 [Skill 3.A] Constructs a that contains characters from

Responses can still earn the point even if they do not include all characters other than in the constructed string

Responses will not earn the point if they do not create a new

+1 [Skill 3.A] Adds preceding and following substring of the identified position in to the constructed

Responses can still earn the point even if they:

· are off by one when finding the initial or final characters

· identify the wrong position or include the identified position when adding characters to the constructed string

Responses will not earn the point if they do not identify a position

+1 [Skill 3.C] Returns a containing the new key with removed

Responses will not earn the point if they:

· incorrectly determine that is in

· do not include all characters other than

· exclude something other than in the returned string

· construct the new incorrectly

-1 (w) Extraneous code that causes side-effect (e.g., printing to output, incorrect precondition check)

-1 (x) Local variables used but none declared

Canonical Solution:

Alternate Canonical Solution:

AP Computer Science A Page 19 of 133


Scoring Guide

Unit 4 FRQ

0 1 2 3 4 5

Total number of points earned (minus penalties) is equal to 5.

+1 Locates in (Points earned)


+1 Returns if is not in (Points earned)
+1 Constructs a that contains characters from (Points earned)
+1 Adds preceding and following substring of the identified position in to the constructed
(Points earned)
+1 Returns a containing the new key with removed (Points earned)
-1 [penalty] (w) Extraneous code that causes side-effect (e.g., printing to output, incorrect precondition
check) (General penalties)
-1 [penalty] (x) Local variables used but none declared (General penalties)

Canonical Solution:

Page 20 of 133 AP Computer Science A


Scoring Guide

Unit 4 FRQ

Alternate Canonical Solution:

Part B – variable count

Select a point value to view scoring criteria, solutions, and/or examples and to score the response. +1 indicates a point
earned and -1 indicates a general or question-specific penalty.

+1 [Skill 3.B] The response identifies properties of the new variable:

· or "integer"

· not local to a method

Responses can still earn the point even if they specify the variable as an instance variable

Responses will not earn the point if they describe a change to the method header

+1 [Skill 3.B] The response describes how the method changes:

AP Computer Science A Page 21 of 133


Scoring Guide

Unit 4 FRQ

· would change to increment the new variable if changes

Responses can still earn the point even if they describe a change to the method header

Responses only earn the point if all described components are plausible, accurate, and consistent as related to the problem

0 1 2

Total number of points earned (minus penalties) is equal to 2.

+1 The response identifies properties of the new variable (Points earned):


· or "integer"
· not local to a method
+1 The response describes how the method changes (Points earned):
· would change to increment the new variable if changes

Page 22 of 133 AP Computer Science A


Scoring Guide

Unit 4 FRQ

SHOW ALL YOUR WORK. REMEMBER THAT PROGRAM SEGMENTS ARE TO BE WRITTEN IN JAVA.

Assume that the classes listed in the Java Quick Reference have been imported where appropriate.
Unless otherwise noted in the question, assume that parameters in method calls are not null and that methods are
called only when their preconditions are satisfied.
In writing solutions for each question, you may use any of the accessible methods that are listed in classes defined in
that question. Writing significant amounts of code that can be replaced by a call to one of these methods will not
receive full credit.

This question involves the use of check digits, which can be used to help detect if an error has occurred when a number is
entered or transmitted electronically. An algorithm for computing a check digit, based on the digits of a number, is provided in
part (a).

The CheckDigit class is shown below. You will write two methods of the CheckDigit class.

public class CheckDigit


{
/** Returns the check digit for num, as described in part (a).
* Precondition: The number of digits in num is between one and six,
inclusive.
* num >= 0
*/
public static int getCheck(int num)
{
/* to be implemented in part (a) */
}

/** Returns true if numWithCheckDigit is valid, or false otherwise, as


described in part (b).
* Precondition: The number of digits in numWithCheckDigit is between two
and seven, inclusive.
* numWithCheckDigit >= 0
*/
public static boolean isValid(int numWithCheckDigit)
{
/* to be implemented in part (b) */
}

/** Returns the number of digits in num. */


public static int getNumberOfDigits(int num)
{
/* implementation not shown */
}

/** Returns the nth digit of num.


* Precondition: n >= 1 and n <= the number of digits in num
*/
public static int getDigit(int num, int n)
{

AP Computer Science A Page 23 of 133


Scoring Guide

Unit 4 FRQ

/* implementation not shown */


}

// There may be instance variables, constructors, and methods not shown.


}

Page 24 of 133 AP Computer Science A


Scoring Guide

Unit 4 FRQ

5. (a) Write the getCheck method, which computes the check digit for a number according to the following rules.

Multiply the first digit by 7, the second digit (if one exists) by 6, the third digit (if one exists) by 5, and so on.
The length of the method's int parameter is at most six; therefore, the last digit of a six-digit number will be
multiplied by 2.
Add the products calculated in the previous step.
Extract the check digit, which is the rightmost digit of the sum calculated in the previous step.

The following are examples of the check-digit calculation.

Example 1, where num has the value 283415

The sum to calculate is


.
The check digit is the rightmost digit of 106, or 6, and getCheck returns the integer value 6.

Example 2, where num has the value 2183

The sum to calculate is .


The check digit is the rightmost digit of 72, or 2, and getCheck returns the integer value 2.

Two helper methods, getNumberOfDigits and getDigit, have been provided.

getNumberOfDigits returns the number of digits in its int parameter.


getDigit returns the nth digit of its int parameter.

The following are examples of the use of getNumberOfDigits and getDigit.

Method Call Return Value Explanation


getNumberOfDigits(283415) 6 The number 283415 has 6 digits.
getDigit(283415, 1) 2 The first digit of 283415 is 2.
getDigit(283415, 5) 1 The fifth digit of 283415 is 1.

Complete the getCheck method below. You must use getNumberOfDigits and getDigit appropriately
to receive full credit.

/** Returns the check digit for num, as described in part (a).
* Precondition: The number of digits in num is between one and six,
inclusive.
* num >= 0
*/
public static int getCheck(int num)

(b) Write the isValid method. The method returns true if its parameter numWithCheckDigit, which
represents a number containing a check digit, is valid, and false otherwise. The check digit is always the rightmost

AP Computer Science A Page 25 of 133


Scoring Guide

Unit 4 FRQ

digit of numWithCheckDigit.

The following table shows some examples of the use of isValid.

Return
Method Call Explanation
Value
getCheck(159) 2 The check digit for 159 is 2.
The number 1592 is a valid combination of a
isValid(1592) true
number (159) and its check digit (2).
The number 1593 is not a valid combination of a
isValid(1593) false number (159) and its check digit (3) because 2 is the check
digit for 159.

Complete method isValid below. Assume that getCheck works as specified, regardless of what you wrote in
part (a). You must use getCheck appropriately to receive full credit.

/** Returns true if numWithCheckDigit is valid, or false otherwise, as


described in part (b).
* Precondition: The number of digits in numWithCheckDigit is between two
and seven, inclusive.
* numWithCheckDigit >= 0
*/
public static boolean isValid(int numWithCheckDigit)

Part A – getCheck method

Select a point value to view scoring criteria, solutions, and/or examples and to score the response. +1 indicates a point
earned and -1 indicates a general or question-specific penalty.

+1 [Skill 3.A] Calls and .

+1 [Skill 3.C] Calculates one partial sum = digit

+1 [Skill 3.C] Calculates all partial sums (in the context of a loop, no bounds errors).

+1 [Skill 3.C] Returns the last digit of the calculated sum as the check digit.

-1 (w) Extraneous code that causes side-effect (e.g., printing to output, incorrect precondition check)

-1 (x) Local variables used but none declared

Canonical Solution:

Page 26 of 133 AP Computer Science A


Scoring Guide

Unit 4 FRQ

0 1 2 3 4

Total number of points earned (minus penalties) is equal to 4.

+1 Calls and . (Points earned)


+1 Calculates one partial sum = digit . (Points earned)
+1 Calculates all partial sums (in the context of a loop, no bounds errors). (Points earned)
+1 Returns the last digit of the calculated sum as the check digit. (Points earned)
-1 (w) Extraneous code that causes side-effect (e.g., printing to output, incorrect precondition check)
(General penalties)
-1 (x) Local variables used but none declared (General penalties)

Canonical Solution:

Part B – isValid method

Select a point value to view scoring criteria, solutions, and/or examples and to score the response. +1 indicates a point
earned and -1 indicates a general or question-specific penalty.

+1 [Skill 3.C] Obtains check digit of .

+1 [Skill 3.C] Obtains number remaining in after check digit removed.

+1 [Skill 3.A] Calls on number without check digit.

+1 [Skill 3.C] Compares check digit of and return value from

AP Computer Science A Page 27 of 133


Scoring Guide

Unit 4 FRQ

+1 [Skill 3.C] Returns or depending on the result of the previous comparison.

-1 (w) Extraneous code that causes side-effect (e.g., printing to output, incorrect precondition check)

-1 (x) Local variables used but none declared

Canonical Solution:

0 1 2 3 4 5

Total number of points earned (minus penalties) is equal to 5.

+1 Obtains check digit of . (Points earned)


+1 Obtains number remaining in after check digit removed. (Points earned)
+1 Calls on number without check digit. (Points earned)
+1 Compares check digit of and return value from . (Points
earned)
+1 Returns or depending on the result of the previous comparison. (Points earned)
-1 (w) Extraneous code that causes side-effect (e.g., printing to output, incorrect precondition check)
(General penalties)
-1 (x) Local variables used but none declared (General penalties)

Canonical Solution:

Page 28 of 133 AP Computer Science A


Scoring Guide

Unit 4 FRQ

AP Computer Science A Page 29 of 133


Scoring Guide

Unit 4 FRQ

6. Directions: SHOW ALL YOUR WORK. REMEMBER THAT PROGRAM SEGMENTS ARE TO BE
WRITTEN IN JAVA.

Notes:

• Assume that the classes listed in the Java Quick Reference have been imported where appropriate.
• Unless otherwise noted in the question, assume that parameters in method calls are not null and
that methods are called only when their preconditions are satisfied.
• In writing solutions for each question, you may use any of the accessible methods that are listed in
classes defined in that question. Writing significant amounts of code that can be replaced by a call to
one of these methods will not receive full credit.

4. This question involves guessing strings that may or may not appear in a secret phrase. Guesses are obtained
using the getGuess method in the following StringGuess class. You will write one method in the class.

public class StringGuess


{
/** Returns a guess string. Assume that this method never returns the
same string twice.
*/
public static String getGuess()
{ /* implementation not shown */ }

/** Returns the proportion of guesses that appear in phrase, as


described in part (a)
* Precondition
Precondition: num > 0, phrase.length() > 0
*/
public static double checkGuesses(String phrase, int num)
{ /* to be implemented in part (a) */ }

// There may be variables and methods that are not shown.


}

(a) Write the StringGuess method checkGuesses, which obtains num guesses using the getGuess
method. Method checkGuesses returns the proportion of obtained guesses that appear in phrase.

For example, consider the call StringGuess.checkGuesses("open_sesame", 4). If getGuess


returns the values "same", "hello", "open", and "car", then the method call should return 0.5
because, of the four values returned by getGuess, two appear in phrase.

You must use getGuess appropriately to receive full credit.

Complete method checkGuesses.

/** Returns the proportion of guesses that appear in phrase, as described

Page 30 of 133 AP Computer Science A


Scoring Guide

Unit 4 FRQ

in part (a)
* Precondition
Precondition: num > 0, phrase.length() > 0
*/
public static double checkGuesses(String phrase, int num)

(b) A programmer wants to modify the StringGuess class so that the number of guesses analyzed by the
checkGuesses method is a random value between 1 and 100, inclusive, and is generated in the
StringGuess class. For example, in one call to checkGuesses, the number of guesses to analyze might
be 12, and in another call to checkGuesses, the number of guesses to analyze might be 77. Each value
between 1 and 100 must have an equal chance of being used as the number of guesses.

Write a description of how you would change the StringGuess class in order to support this modification. Do
not write the program code for this change.

Make sure to include the following in your response.

• Identify any new or modified variables or methods.


• Describe, for each new or revised variable or method, how it would change or be implemented,
including visibility and type.

Part A – checkGuesses

Select a point value to view scoring criteria, solutions, and/or examples and to score the response. +1 indicates a point
earned and -1 indicates a general or question-specific penalty.

+1 [Skill 3.C] Iterates times

Responses can still earn the point even if they inappropriately return inside the loop

+1 [Skill 3.A] Uses return value

Responses will not earn the point if they call incorrectly

+1 [Skill 3.A] Checks whether a guess appears within

Responses can still earn the point even if they call incorrectly

Responses will not earn the point if they:

· call or incorrectly

· identify multiple occurrences of the same guess for counting

+1 [Skill 3.C] Updates count under appropriate conditions (in the context of a loop)

Responses can still earn the point even if they use incorrect logic to guard the update

Responses will not earn the point if they:

· do not initialize count

AP Computer Science A Page 31 of 133


Scoring Guide

Unit 4 FRQ

· do not use a value returned by to guard the update

+1 [Skill 3.C] Returns a calculated proportion ( )

Responses can still earn the point even if they:

· accumulate count incorrectly

· have no loop but use an statement

Responses will not earn the point if they:

· calculate the proportion incorrectly based on count and

· use integer division inappropriately

-1 (w) Extraneous code that causes side-effect (e.g., printing to output, incorrect precondition check)

-1 (x) Local variables used but none declared

Canonical Solution:

= 0) Line 10: { Line 11: count++; Line 12: } Line 13: } Line 14: return (double) count / num; Line 15: } end code">

0 1 2 3 4 5

Total number of points earned (minus penalties) is equal to 5.

+1 Iterates times (Points earned)


+1 Uses return value (Points earned)
+1 Checks whether a guess appears within (Points earned)
+1 Updates count under appropriate conditions (in the context of a loop) (Points earned)

Page 32 of 133 AP Computer Science A


Scoring Guide

Unit 4 FRQ

+1 Returns a calculated proportion ( ) (Points earned)


-1 [penalty] (w) Extraneous code that causes side-effect (e.g., printing to output, incorrect precondition
check) (General penalties)
-1 [penalty] (x) Local variables used but none declared (General penalties)

Canonical Solution:

= 0) Line 10: { Line 11: count++; Line 12: } Line 13: } Line 14: return (double) count / num; Line 15: } end code">

Part B – Modification to number of guesses

Select a point value to view scoring criteria, solutions, and/or examples and to score the response. +1 indicates a point
earned and -1 indicates a general or question-specific penalty.

+1 [Skill 3.B] The response identifies changes to the method header:

· would change to have only a single parameter

+1 [Skill 3.A] The response describes how the method changes:

· would change to calculate a random number between 1 and 100 before the loop, and use this value in
the loop condition in place of the parameter

Responses can still earn the point even if they do not specify a change to the header

Responses only earn the point if all described components are plausible, accurate, and consistent as related to the problem

0 1 2

Total number of points earned (minus penalties) is equal to 2.

+1 The response identifies changes to the method header (Points earned):


o would change to have only a single parameter

AP Computer Science A Page 33 of 133


Scoring Guide

Unit 4 FRQ

+1 The response describes how the method changes (Points earned):


o would change to calculate a random number between 1 and 100 before the loop, and
use this value in the loop condition in place of the parameter

Page 34 of 133 AP Computer Science A


Scoring Guide

Unit 4 FRQ

7. Directions: SHOW ALL YOUR WORK. REMEMBER THAT PROGRAM SEGMENTS ARE TO BE
WRITTEN IN JAVA.

Notes:

• Assume that the classes listed in the Java Quick Reference have been imported where appropriate.
• Unless otherwise noted in the question, assume that parameters in method calls are not null and
that methods are called only when their preconditions are satisfied.
• In writing solutions for each question, you may use any of the accessible methods that are listed in
classes defined in that question. Writing significant amounts of code that can be replaced by a call to
one of these methods will not receive full credit.

6. This question involves computing an integer based on two input strings. You will write the compute method
of the following Operator class.

public class Operator


{
/** Returns an integer value based on the input string */
public static int transform(String str)
{ /* implementation not shown */ }

/** Returns an integer based on two input strings, as described in part


(a)
* Precondition
Precondition: input and op are not null.
* The length of input is even.
* op is either "$$", "^^", or "##".
*/
public static int compute(String input, String op)
{ /* to be implemented in part (a) */ }

// There may be variables and methods that are not shown.


}

(a) Write the compute method of the Operator class. The method calculates an integer value based on an
input string with even length. The first half and the second half of input are transformed into numeric values
by calls to transform. The numeric values are then used in a calculation based on the mathematical operation
represented by the string, op. The method returns the calculated result.

The helper method transform has been provided. The method returns an integer value based on its String
parameter. For example, the method call transform("pear") might return the int value 3.

The mathematical operations represented by op are described in the following table. Assume that value1 is
the numeric value obtained by calling transform on the first half of input and value2 is the numeric
value obtained by calling transform on the second half of input.

AP Computer Science A Page 35 of 133


Scoring Guide

Unit 4 FRQ

Value of op Mathematical Operation Description


"$$" Addition value1 plus value2
"^^" Multiplication value1 times value2
"##" Subtraction value1 minus value2

For example, assume that calls to transform are made from the Operator class and that
transform("orang") returns 2 and transform("epear") returns 6. Then the method call
Operator.compute("orangepear", "$$") should return 8.

As another example, the method call Operator.compute("orangepear", "##") should return -4.

Complete method compute. You must use transform appropriately to receive full credit.

/** Returns an integer based on two input strings, as described in part


(a)
* Precondition
Precondition: input and op are not null.
* The length of input is even.
* op is either "$$", "^^", or "##".
*/
public static int compute(String input, String op)

(b) A programmer wants to modify the Operator class so that the compute method has a single String
parameter containing both input and op.

Write a description of how you would change the Operator class in order to support this modification. Do not
write the program code for this change.

Make sure to include the following in your response.

• Identify any new or modified variables or methods.


• Describe, for each new or revised variable or method, how it would change or be implemented,
including visibility and type.

Part A – compute

Select a point value to view scoring criteria, solutions, and/or examples and to score the response. +1 indicates a point
earned and -1 indicates a general or question-specific penalty.

+1 [Skill 3.A] Divides the input string into two substrings of equal length

Responses will not earn the point if they:

· create overlapping substrings

· have a bounds error

+1 [Skill 3.A] Calls on two substrings of input string

Page 36 of 133 AP Computer Science A


Scoring Guide

Unit 4 FRQ

Responses can still earn the point even if they:

· divide the string incorrectly into two halves

· call incorrectly

Responses will not earn the point if they call incorrectly

+1 [Skill 3.A] Compares to 3 possible values (in the context of a conditional statement)

Responses can still earn the point even if they:

· assign incorrect values to the result to return based on incorrect comparisons

· divide the string incorrectly into two parts

Responses will not earn the point if they compare to possible operators using

+1 [Skill 3.C] Performs the calculation based on the value of and return values

Responses can still earn the point even if they:

· use incorrectly calculated operands

· use incorrectly ordered operands in case of subtraction

Responses will not earn the point if they pair an incorrect mathematical operator with any of the 3 values of

+1 [Skill 3.C] Calculates and returns appropriate value in all cases (algorithm point)

Responses can still earn the point even if they:

· use incorrectly calculated operands

· compare to possible operators using

-1 (w) Extraneous code that causes side-effect (e.g., printing to output, incorrect precondition check)

-1 (x) Local variables used but none declared

Canonical Solution:

AP Computer Science A Page 37 of 133


Scoring Guide

Unit 4 FRQ

0 1 2 3 4 5

Total number of points earned (minus penalties) is equal to 5.

+1 Divides the input string into two substrings of equal length (Points earned)
+1 Calls on two substrings of input string (Points earned)
+1 Compares to 3 possible values (in the context of a conditional statement) (Points earned)
+1 Performs the calculation based on the value of and return values (Points earned)
+1 Calculates and returns appropriate value in all cases (algorithm point) (Points earned)
-1 [penalty] (w) Extraneous code that causes side-effect (e.g., printing to output, incorrect precondition
check) (General penalties)
-1 [penalty] (x) Local variables used but none declared (General penalties)

Canonical Solution:

Page 38 of 133 AP Computer Science A


Scoring Guide

Unit 4 FRQ

Part B – Operator class updates

Select a point value to view scoring criteria, solutions, and/or examples and to score the response. +1 indicates a point
earned and -1 indicates a general or question-specific penalty.

+1 [Skill 3.B] The response identifies changes to the method header:

· would be modified to have a single parameter

+1 [Skill 3.A] The response describes how the method changes:

· the method would need to be changed to split from

Responses can still earn the point even if they:

o do not specify a change to the method header

o assume any order of and in the new string

Responses only earn the point if all described components are plausible, accurate, and consistent as related to the problem

0 1 2

AP Computer Science A Page 39 of 133


Scoring Guide

Unit 4 FRQ

Total number of points earned (minus penalties) is equal to 2.

+1 The response identifies changes to the method header (Points earned):


o would be modified to have a single parameter
+1 The response describes how the method changes (Points earned):
o the method would need to be changed to split from

Page 40 of 133 AP Computer Science A


Scoring Guide

Unit 4 FRQ

8. Directions: SHOW ALL YOUR WORK. REMEMBER THAT PROGRAM SEGMENTS ARE TO BE
WRITTEN IN JAVA.

Notes:

• Assume that the classes listed in the Java Quick Reference have been imported where appropriate.
• Unless otherwise noted in the question, assume that parameters in method calls are not null and
that methods are called only when their preconditions are satisfied.
• In writing solutions for each question, you may use any of the accessible methods that are listed in
classes defined in that question. Writing significant amounts of code that can be replaced by a call to
one of these methods will not receive full credit.

4. This question involves analyzing numbers that are obtained using the getNumber method in the following
NumberChecker class. You will write one method in the class.

public class NumberChecker


{
/** Returns an int value to be analyzed */
public static int getNumber()
{ /* implementation not shown */ }

/** Returns true if x is a target number and returns false otherwise */


public static boolean isTarget(int x)
{ /* implementation not shown */ }

/** Analyzes values obtained using the getNumber method, as described


in part (a)
* Precondition
Precondition: 0 < n < max
*/
public static int countNumbers(int n, int max)
{ /* to be implemented in part (a) */ }

// There may be variables and methods that are not shown.


}

(a) Write method countNumbers, which obtains values using the getNumber method and returns the
number of calls to getNumber that are made until n values are obtained that meet both of the following
criteria.

• Is NOT a target number, as determined by the isTarget method


• Is divisible by 3

If max calls are made to getNumber without obtaining n values that meet the criteria, -1 is returned.

AP Computer Science A Page 41 of 133


Scoring Guide

Unit 4 FRQ

A helper method, isTarget, has been provided. The method returns true if its integer parameter is a target
number and returns false otherwise. You must use isTarget appropriately to receive full credit.

Complete method countNumbers.

/** Analyzes values obtained using the getNumber method, as described in


part (a)
* Precondition
Precondition: 0 < n < max
*/
public static int countNumbers(int n, int max)

(b) A programmer wants to modify the NumberChecker class so that in the countNumbers method, the
check for divisibility by an integer can vary between method calls. For example, in one call to
countNumbers, the method might check for divisibility by , and in another call to countNumbers, the
method might check for divisibility by .

The programmer would like to implement this change without making any changes to the signature of the
countNumbers method or overloading countNumbers.

Write a description of how you would change the NumberChecker class in order to support this modification.
Do not write the program code for this change.

Make sure to include the following in your response.

• Identify any new or modified variables or methods.


• Describe, for each new or revised variable or method, how it would change or be implemented,
including visibility and type.

Part A – countNumbers

Select a point value to view scoring criteria, solutions, and/or examples and to score the response. +1 indicates a point
earned and -1 indicates a general or question-specific penalty.

+1 [Skill 3.C] Iterates until values that meet criteria are found or maximum number of input values are examined

Responses can still earn the point even if they:

· incorrectly count the number of input values

· Incorrectly count the input values meeting criteria

· do not initialize either counter

Responses will not earn the point if they do not attempt to get the next number inside the loop

+1 [Skill 3.A] Calls (in the context of a condition or loop)

Responses can still earn the point even if they do not use a loop

Responses will not earn the point if they:

Page 42 of 133 AP Computer Science A


Scoring Guide

Unit 4 FRQ

· call incorrectly

· do not use the return value in a condition

+1 [Skill 3.C] Counts all numbers

Responses can still earn the point even if they terminate the loop under incorrect conditions

Responses will not earn the point if they:

· do not initialize the counter

· do not increment the counter in the context of a loop

· do not store and use the return value

+1 [Skill 3.C] Counts the numbers that meet criteria

Responses can still earn the point even if they:

· terminate the loop under incorrect conditions

· do not initialize the counter of values examined

· skip some numbers

· do not use the return value

· do not negate the return value

· call incorrectly

Responses will not earn the point if they:

· do not initialize the counter of values that meet criteria

· do not increment the counter in the context of a comparison of and a call to within a loop

· do not call on an input number

+1 [Skill 3.C] Returns number of input values examined until values found that meet criteria, or otherwise

Responses can still earn the point even if they accumulate counts incorrectly

-1 (w) Extraneous code that causes side-effect (e.g., printing to output, incorrect precondition check)

-1 (x) Local variables used but none declared

Canonical Solution:

AP Computer Science A Page 43 of 133


Scoring Guide

Unit 4 FRQ

Alternate Canonical Solution:

Page 44 of 133 AP Computer Science A


Scoring Guide

Unit 4 FRQ

0 1 2 3 4 5

Total number of points earned (minus penalties) is equal to 5.

+1 Iterates until values that meet criteria are found or maximum number of input values are examined
(Points earned)
+1 Calls (in the context of a condition or loop) (Points earned)
+1 Counts all numbers (Points earned)
+1 Counts the numbers that meet criteria (Points earned)
+1 Returns number of input values examined until values found that meet criteria, or otherwise
(Points earned)
-1 [penalty] (w) Extraneous code that causes side-effect (e.g., printing to output, incorrect precondition
check) (General penalties)
-1 [penalty] (x) Local variables used but none declared (General penalties)

Canonical Solution:

Alternate Canonical Solution:

AP Computer Science A Page 45 of 133


Scoring Guide

Unit 4 FRQ

Part B – countNumbers changing criteria

Select a point value to view scoring criteria, solutions, and/or examples and to score the response. +1 indicates a point
earned and -1 indicates a general or question-specific penalty.

+1 [Skill 3.B] The response identifies properties of the new variable:

· or "integer"

· not local to a method

Responses can still earn the point even if they:

o specify the variable as an instance variable

o describe a local variable that is assigned a value only once during the method call, where the value is generated
randomly or from user input

Responses will not earn the point if they describe a change to the header

+1 [Skill 3.B] The response describes how the method changes:

· would change so that it uses the new variable instead of always using

Responses can still earn the point even if they describe a change to the method header

Responses will not earn the point if the same divisor is not used for all numbers

Responses only earn the point if all described components are plausible, accurate, and consistent as related to the problem

Page 46 of 133 AP Computer Science A


Scoring Guide

Unit 4 FRQ

0 1 2

Total number of points earned (minus penalties) is equal to 2.

+1 The response identifies properties of the new variable (Points earned):


o or "integer"
o not local to a method
+1 The response describes how the method changes (Points earned):
o would change so that it uses the new variable instead of always using

AP Computer Science A Page 47 of 133


Scoring Guide

Unit 4 FRQ

9. Directions: SHOW ALL YOUR WORK. REMEMBER THAT PROGRAM SEGMENTS ARE TO BE
WRITTEN IN JAVA.

Notes:

• Assume that the classes listed in the Java Quick Reference have been imported where appropriate.
• Unless otherwise noted in the question, assume that parameters in method calls are not null and
that methods are called only when their preconditions are satisfied.
• In writing solutions for each question, you may use any of the accessible methods that are listed in
classes defined in that question. Writing significant amounts of code that can be replaced by a call to
one of these methods will not receive full credit.

4. This question involves analyzing strings. You will write the countRepeat method of the following
StringAnalyzer class.

public class StringAnalyzer


{
/** Returns a count of how many times smallStr occurs in largeStr, as
* described in part (a)
* Precondition
Precondition: largeStr is not null; smallStr is not null.
* The length of smallStr is less than the length of
largeStr.
*/
public static int countRepeat(String largeStr, String smallStr)
{ /* to be implemented in part (a) */ }

// There may be variables and methods that are not shown.


}

(a) The countRepeat method is used to count and return the number of times the string parameter
smallStr appears in the string parameter largeStr. In the case of overlapping occurrences of
smallStr, only the first occurrence is included in the overall count, as shown in the second and third calls to
countRepeat in the following table of examples.

Call to countRepeat Return Value


StringAnalyzer.countRepeat("BAAB", "AA") 1
StringAnalyzer.countRepeat("AAAAA", "AA") 2
StringAnalyzer.countRepeat("AABABABAA", "ABA") 2
StringAnalyzer.countRepeat("ABBAABB", "ABA") 0

Complete method countRepeat.

Page 48 of 133 AP Computer Science A


Scoring Guide

Unit 4 FRQ

/** Returns a count of how many times smallStr occurs in largeStr,


* as described in part (a)
* Precondition
Precondition: largeStr is not null; smallStr is not null.
* The length of smallStr is less than the length of
largeStr.
*/
public static int countRepeat(String largeStr, String smallStr)

(b) A programmer would like to modify the StringAnalyzer class to limit the length of the large string that
can be passed as input to countRepeat. The limit could vary between calls to countRepeat. A call to
countRepeat with a value of largeStr that is longer than the maximum length would return –1. The
programmer would like to implement this change without making any changes to the signature of the
countRepeat method or overloading countRepeat.

Write a description of how you would change the StringAnalyzer class in order to support this
modification. Do not write the program code for this change.

Make sure to include the following in your response.

• Identify any new or modified variables or methods.


• Describe, for each new or revised variable or method, how it would change or be implemented,
including visibility and type.

Part A – countRepeat

Select a point value to view scoring criteria, solutions, and/or examples and to score the response. +1 indicates a point
earned and -1 indicates a general or question-specific penalty.

+1 [Skill 3.C] Traverses (no bounds errors)

Responses will not earn the point if they:

· do not use in the loop

· calculate the length of incorrectly for use in the traversal of

+1 [Skill 3.A] Gets a substring of length of from

Responses can still earn the point even if they calculate the length of using an incorrect call to

Responses will not earn the point if they do not use the length of to compare substrings of equal length

+1 [Skill 3.A] Uses and a substring of to guard the increment of the counter and update of the loop
control variable

Responses can still earn the point even if they:

· get an incorrect substring from

· use incorrect logic to guard the increments

AP Computer Science A Page 49 of 133


Scoring Guide

Unit 4 FRQ

Responses will not earn the point if they use instead of

+1 [Skill 3.C] Updates loop control variable and counter based on result of comparison (algorithm)

Responses can still earn the point even if they calculate the length of using an incorrect call to

Responses will not earn the point if they:

· do not initialize the loop control variable or counter

· use incorrect logic to guard the increments

· update loop control variable by something other than the length of

· count overlapping occurrences (for a reason other than incorrect length)

+1 [Skill 3.C] Returns count of non-overlapping substring occurrences

Responses can still earn the point even if they:

· accumulate count incorrectly

· have a bounds error

Responses will not earn the point if they return early

-1 (w) Extraneous code that causes side-effect (e.g., printing to output, incorrect precondition check)

-1 (x) Local variables used but none declared

Canonical Solution:

Page 50 of 133 AP Computer Science A


Scoring Guide

Unit 4 FRQ

Alternate Canonical Solution:

0 1 2 3 4 5

Total number of points earned (minus penalties) is equal to 5.

+1 Traverses (no bounds errors) (Points earned)

AP Computer Science A Page 51 of 133


Scoring Guide

Unit 4 FRQ

+1 Gets a substring of length of from (Points earned)


+1 Uses and a substring of to guard the increment of the counter and update of the
loop control variable (Points earned)
+1 Updates loop control variable and counter based on result of comparison (algorithm) (Points earned)
+1 Returns count of non-overlapping substring occurrences (Points earned)
-1 [penalty] (w) Extraneous code that causes side-effect (e.g., printing to output, incorrect precondition
check) (General penalties)
-1 [penalty] (x) Local variables used but none declared (General penalties)

Canonical Solution:

Alternate Canonical Solution:

Page 52 of 133 AP Computer Science A


Scoring Guide

Unit 4 FRQ

Part B – StringAnalyzer

Select a point value to view scoring criteria, solutions, and/or examples and to score the response. +1 indicates a point
earned and -1 indicates a general or question-specific penalty.

+1 [Skill 3.B] The response identifies properties of the new variable:

· or "integer"

· not local to a method

Responses can still earn the point even if they:

o specify the variable as an instance variable

o do not describe a variable or identify a type, but describe an appropriate identified value as generated only once during
the method call, randomly or from user input

Responses will not earn the point if they describe a change to the method header

+1 [Skill 3.B] The response describes how the method changes:

· method would need to change so that it checks if the length of is less than the static variable
and returns if so

Responses can still earn the point even if they describe a change to the method header

Responses only earn the point if all described components are plausible, accurate, and consistent as related to the problem

0 1 2

AP Computer Science A Page 53 of 133


Scoring Guide

Unit 4 FRQ

Total number of points earned (minus penalties) is equal to 2.

+1 The response identifies properties of the new variable (Points earned):


o or "integer"
o not local to a method
+1 The response describes how the method changes (Points earned):
o method would need to change so that it checks if the length of is less than the
static variable and returns if so

Page 54 of 133 AP Computer Science A


Scoring Guide

Unit 4 FRQ

10. This question involves reasoning about a simulation of a frog hopping in a straight line. The frog attempts to hop
to a goal within a specified number of hops. The simulation is encapsulated in the following FrogSimulation class.
You will write two of the methods in this class.

a. Write the simulate method, which simulates the frog attempting to hop in a straight line to a goal from
the frog's starting position of 0 within a maximum number of hops. The method returns true if the frog
successfully reached the goal within the maximum number of hops; otherwise, the method returns false.

The FrogSimulation class provides a method called hopDistance that returns an integer representing the
distance (positive or negative) to be moved when the frog hops. A positive distance represents a move
toward the goal. A negative distance represents a move away from the goal. The returned distance may
vary from call to call. Each time the frog hops, its position is adjusted by the value returned by a call to
the hopDistance method.

The frog hops until one of the following conditions becomes true:

• The frog has reached or passed the goal.

• The frog has reached a negative position.

• The frog has taken the maximum number of hops without reaching the goal.

AP Computer Science A Page 55 of 133


Scoring Guide

Unit 4 FRQ

The following example shows a declaration of a FrogSimulation object for which the goal distance is 24
inches and the maximum number of hops is 5. The table shows some possible outcomes of calling the
simulate method.

FrogSimulation sim = new FrogSimulation(24, 5);

Complete method simulate below. You must use hopDistance appropriately to receive full credit.

/** Simulates a frog attempting to reach the goal as described in part (a). * Returns true if the frog
successfully reached or passed the goal during the simulation; * false otherwise. */

public boolean simulate()

b. Write the runSimulations method, which performs a given number of simulations and returns the
proportion of simulations in which the frog successfully reached or passed the goal. For example, if the
parameter passed to runSimulations is 400, and 100 of the 400 simulate method calls returned true, then
the runSimulations method should return 0.25.

Page 56 of 133 AP Computer Science A


Scoring Guide

Unit 4 FRQ

Complete method runSimulations below. Assume that simulate works as specified, regardless of what
you wrote in part (a). You must use simulate appropriately to receive full credit.

Part A

Intent: Simulate the distance traveled by a hopping frog

1 point is earned for: Calls hopDistance and uses returned distance to adjust (or represent) the frog’s position

1 point is earned for: Initializes and accumulates the frog’s position at most maxHops times (must be in context of a
loop)

1 point is earned for: Determines if a distance representing multiple hops is at least goalDistance

1 point is earned for: Determines if a distance representing multiple hops is less than starting position

1 point is earned for: Returns true if goal ever reached, false if goal never reached or position ever less than starting
position

public boolean simulate()

int position = 0;

for (int count = 0; count < maxHops; count++)

position += hopDistance();

if (position >= goalDistance)

return true;

else if (position < 0)

return false;

AP Computer Science A Page 57 of 133


Scoring Guide

Unit 4 FRQ

return false;

0 1 2 3 4 5

Student response earns 5 of the following 5 point(s)

Intent: Simulate the distance traveled by a hopping frog

1 point is earned for: Calls hopDistance and uses returned distance to adjust (or represent) the frog’s position

1 point is earned for: Initializes and accumulates the frog’s position at most maxHops times (must be in context of a
loop)

1 point is earned for: Determines if a distance representing multiple hops is at least goalDistance

1 point is earned for: Determines if a distance representing multiple hops is less than starting position

1 point is earned for: Returns true if goal ever reached, false if goal never reached or position ever less than starting
position

public boolean simulate()

int position = 0;

for (int count = 0; count < maxHops; count++)

position += hopDistance();

if (position >= goalDistance)

return true;

else if (position < 0)

Page 58 of 133 AP Computer Science A


Scoring Guide

Unit 4 FRQ

return false;

return false;

Part B

Intent: Determine the proportion of successful frog hopping simulations

1 point is earned for: Calls simulate the specified number of times (no bounds errors)

1 point is earned for: Initializes and accumulates a count of true results

1 point is earned for: Calculates proportion of successful simulations using double arithmetic

1 point is earned for: Returns calculated value

public double runSimulations(int num)

int countSuccess = 0;

for (int count = 0; count < num; count++)

if(simulate())

countSuccess++;

return (double)countSuccess / num;

0 1 2 3 4

Student response earns 4 of the following 4 point(s)

AP Computer Science A Page 59 of 133


Scoring Guide

Unit 4 FRQ

Intent: Determine the proportion of successful frog hopping simulations

1 point is earned for: Calls simulate the specified number of times (no bounds errors)

1 point is earned for: Initializes and accumulates a count of true results

1 point is earned for: Calculates proportion of successful simulations using double arithmetic

1 point is earned for: Returns calculated value

public double runSimulations(int num)

int countSuccess = 0;

for (int count = 0; count < num; count++)

if(simulate())

countSuccess++;

return (double)countSuccess / num;

Page 60 of 133 AP Computer Science A


Scoring Guide

Unit 4 FRQ

11. Directions: SHOW ALL YOUR WORK. REMEMBER THAT PROGRAM SEGMENTS ARE TO BE
WRITTEN IN JAVA.

Notes:

• Assume that the classes listed in the Java Quick Reference have been imported where appropriate.
• Unless otherwise noted in the question, assume that parameters in method calls are not null and
that methods are called only when their preconditions are satisfied.
• In writing solutions for each question, you may use any of the accessible methods that are listed in
classes defined in that question. Writing significant amounts of code that can be replaced by a call to
one of these methods will not receive full credit.

6. This question involves translating a string consisting of a single uppercase letter based on a substitution rule.

The class Secret contains methods used to translate letters. You will write one method in this class. A partial
declaration of the Secret class is shown below.

public class Secret


{
/** Returns the single-character String produced by applying the
substitution rule to
* the given letter, as described in part (a)
* Precondition
Precondition: letter consists of one uppercase letter.
* rule has at least letters and all letters are
uppercase and unique.
*/
public static String newLetter(String letter, String rule)
{ /* to be implemented in part (a) */ }

// There may be variables and methods that are not shown.


}

(a) Write the Secret method newLetter, which is used to translate a string consisting of a single
uppercase letter based on a substitution rule. The parameter letter is the one-letter string to be translated. The
parameter rule is the substitution rule.

A substitution rule is represented by a string of at least two letters. All the letters in the substitution rule are
uppercase and unique. A sample substitution rule is "ABC".

The substitution rule is used to translate an uppercase letter as follows.

• If the letter is contained in the rule, the method returns the next letter in the rule. For example, if the
rule is "CBA", "C" would be translated to "B", and "B" would be translated to "A". If the
letter appears at the end of the rule, the first letter of the rule is returned. Using the rule "CBA",
"A" would be translated to "C".

AP Computer Science A Page 61 of 133


Scoring Guide

Unit 4 FRQ

• If the letter does not appear in the rule, it is returned. For example, "F" would be returned using the
rule "CBA" because "F" does not appear in the rule.

The following table shows the results of several calls to newLetter.

Method Call Return Value


Secret.newLetter("G", "GXAD") "X"
Secret.newLetter("D", "GXAD") "G"
Secret.newLetter("M", "GXAD") "M"

Complete method newLetter.

/** Returns the single-character String produced by applying the


substitution rule to
* the given letter, as described in part (a)
* Precondition
Precondition: letter consists of one uppercase letter.
* rule has at least letters and all letters are
uppercase and unique.
*/
public static String newLetter(String letter, String rule)

(b) The programmer would like to modify the Secret class so that the substitution rule is stored in the class
instead of passed as a parameter. The modification would need to support the ability for a calling program to
change the rule.

Write a description of how you would change the Secret class in order to support this modification. Do not
write the program code for this change.

Make sure to include the following in your response.

• Identify any new or modified variables or methods.


• Describe, for each new or revised variable or method, how it would change or be implemented,
including visibility and type.

Part A – newLetter

Select a point value to view scoring criteria, solutions, and/or examples and to score the response. +1 indicates a point
earned and -1 indicates a general or question-specific penalty.

+1 [Skill 3.A] Locates in

Responses can still earn the point even if they:

· are off by one when using a loop to locate

· return early from a loop

Page 62 of 133 AP Computer Science A


Scoring Guide

Unit 4 FRQ

+1 [Skill 3.C] Returns if is not in

Responses can still earn the point even if they incorrectly determine whether is in

+1 [Skill 3.A] Checks for in the last position of

Responses can still earn the point even if they are off by one in calculating the last position

+1 [Skill 3.A] Identifies a single character in if is in

Responses can still earn the point even if they:

· identify a instead of a

· do not return the identified character

+1 [Skill 3.C] Returns the appropriate 1-character in if is in (algorithm)

Responses will not earn the point if they:

· incorrectly determine whether is in

· return a character off by one when is in the last position

· return a instead of a

· are off by one when using a loop to locate

· return early from a loop

-1 (w) Extraneous code that causes side-effect (e.g., printing to output, incorrect precondition check)

-1 (x) Local variables used but none declared

-1 (t) Accesses single characters incorrectly, including calling incorrectly or using array or syntax

Canonical Solution:

AP Computer Science A Page 63 of 133


Scoring Guide

Unit 4 FRQ

0 1 2 3 4 5

Total number of points earned (minus penalties) is equal to 5.

+1 Locates in (Points earned)


+1 Returns if is not in (Points earned)
+1 Checks for in the last position of (Points earned)
+1 Identifies a single character in if is in (Points earned)
+1 Returns the appropriate 1-character in if is in (algorithm) (Points earned)
-1 [penalty] (w) Extraneous code that causes side-effect (e.g., printing to output, incorrect precondition
check) (General penalties)
-1 [penalty] (x) Local variables used but none declared (General penalties)
-1 [penalty] (t) Accesses single characters incorrectly, including calling incorrectly or using
array or syntax (General penalties)

Canonical Solution:

Part B – variable to store rule

Select a point value to view scoring criteria, solutions, and/or examples and to score the response. +1 indicates a point
earned and -1 indicates a general or question-specific penalty.

+1 [Skill 3.B] The response identifies properties of the new variable:

· or "string"

· not local to a method

Responses can still earn the point even if they specify the variable as an instance variable

Page 64 of 133 AP Computer Science A


Scoring Guide

Unit 4 FRQ

+1 [Skill 3.B] The response describes how the method changes:

· would change to have only a single parameter (the letter to translate) and would access the rule
using the new variable

Responses only earn the point if all described components are plausible, accurate, and consistent as related to the problem

0 1 2

Total number of points earned (minus penalties) is equal to 2.

+1 The response identifies properties of the new variable (Points earned):


· or "string"
· not local to a method
+1 The response describes how the method changes (Points earned):
· would change to have only a single parameter (the letter to translate) and would
access the rule using the new variable

AP Computer Science A Page 65 of 133


Scoring Guide

Unit 4 FRQ

12. Directions: SHOW ALL YOUR WORK. REMEMBER THAT PROGRAM SEGMENTS ARE TO BE
WRITTEN IN JAVA.

Notes:

• Assume that the classes listed in the Java Quick Reference have been imported where appropriate.
• Unless otherwise noted in the question, assume that parameters in method calls are not null and
that methods are called only when their preconditions are satisfied.
• In writing solutions for each question, you may use any of the accessible methods that are listed in
classes defined in that question. Writing significant amounts of code that can be replaced by a call to
one of these methods will not receive full credit.

6. The MysteryNumber class contains methods used to analyze properties of numbers. You will write one
method of the MysteryNumber class.

public class MysteryNumber


{
/** Returns true if num is a mystery number and false otherwise */
private static boolean isMystery(int num)
{ /* implementation not shown */ }

/** Returns the nth mystery number starting with 1, as described in


part (a)
* Precondition
Precondition: 1 <= n
* There are at least n mystery numbers between 1 and
* Integer.MAX_VALUE.
*/
public static int nthMysteryNumber(int n)
{ /* to be implemented in part (a) */ }

// There may be variables and methods that are not shown.


}

(a) Write the static method nthMysteryNumber, which returns the mystery number, starting with . A
helper method, isMystery, has been provided. The method returns true if its parameter is a mystery
number and returns false otherwise.

Assume that the following numbers are the first mystery numbers and that there are more mystery numbers than
the ones shown below.

, , , , , ,

The following table shows examples of values returned by nthMysteryNumber.

Page 66 of 133 AP Computer Science A


Scoring Guide

Unit 4 FRQ

Method Call Return Value


MysteryNumber.nthMysteryNumber(3) 6
MysteryNumber.nthMysteryNumber(5) 11

Complete method nthMysteryNumber. You must use isMystery appropriately to receive full credit.

/** Returns the nth mystery number starting with 1, as described in part
(a)
* Precondition
Precondition: 1 <= n
* There are at least n mystery numbers between 1 and
* Integer.MAX_VALUE.
*/
public static int nthMysteryNumber(int n)

(b) A programmer wants to modify the MysteryNumber class so that the nthMysteryNumber method
returns the nth mystery number that is greater than or equal to a given integer value. For example, in one call to
nthMysteryNumber, the method might return the third mystery number that is greater than or equal to , and
in another call to nthMysteryNumber, the method might return the fifth mystery number that is greater than
or equal to .

Write a description of how you would change the MysteryNumber class in order to support this modification.
Do not write the program code for this change.

Make sure to include the following in your response.

• Identify any new or modified variables or methods.


• Describe, for each new or revised variable or method, how it would change or be implemented,
including visibility and type.

Part A – nthMysteryNumber

Select a point value to view scoring criteria, solutions, and/or examples and to score the response. +1 indicates a point
earned and -1 indicates a general or question-specific penalty.

+1 [Skill 3.C] Loops through all numbers between and mystery number, inclusive

Responses can still earn the point even if they return early inside the loop

+1 [Skill 3.A] Calls using an

Responses will not earn the point if they call incorrectly

+1 [Skill 3.C] Increments count of mystery numbers based on comparison of return value and

Responses can still earn the point even if they call incorrectly

Responses will not earn the point if they:

AP Computer Science A Page 67 of 133


Scoring Guide

Unit 4 FRQ

· do not initialize the count variable

· increment the count incorrectly

+1 [Skill 3.C] Increments argument used in call to (in the context of a loop)

Responses can still earn the point even if they call incorrectly

Responses will not earn the point if they do not increment the argument in all cases

+1 [Skill 3.C] Identifies and returns the mystery number

Responses can still earn the point even if they do not increment the argument to in all cases

-1 (w) Extraneous code that causes side-effect (e.g., printing to output, incorrect precondition check)

-1 (x) Local variables used but none declared

Canonical Solution:

Alternate Canonical Solution:

Page 68 of 133 AP Computer Science A


Scoring Guide

Unit 4 FRQ

0 1 2 3 4 5

Total number of points earned (minus penalties) is equal to 5.

+1 Loops through all numbers between and mystery number, inclusive (Points earned)
+1 Calls using an (Points earned)
+1 Increments count of mystery numbers based on comparison of return value and
(Points earned)
+1 Increments argument used in call to (in the context of a loop) (Points earned)
+1 Identifies and returns the mystery number (Points earned)
-1 [penalty] (w) Extraneous code that causes side-effect (e.g., printing to output, incorrect precondition
check) (General penalties)
-1 [penalty] (x) Local variables used but none declared (General penalties)

Canonical Solution:

AP Computer Science A Page 69 of 133


Scoring Guide

Unit 4 FRQ

Alternate Canonical Solution:

Part B – MysteryNumber updates

Select a point value to view scoring criteria, solutions, and/or examples and to score the response. +1 indicates a point
earned and -1 indicates a general or question-specific penalty.

+1 [Skill 3.B] The response identifies changes to the method header:

· would need an additional or "integer" parameter not local to a method

Responses can still earn the point even if they describe a new variable in the class that is not explicitly stated as local to
the method

+1 [Skill 3.C] The response describes how the method changes:

· the method begins counting mystery numbers starting at the given parameter instead of starting at 1

Responses can still earn the point even if they do not specify a change to the method header

Page 70 of 133 AP Computer Science A


Scoring Guide

Unit 4 FRQ

Responses only earn the point if all described components are plausible, accurate, and consistent as related to the problem

0 1 2

Total number of points earned (minus penalties) is equal to 2.

+1 The response identifies changes to the method header (Points earned):


o would need an additional or "integer" parameter not local to a method not
local to a method
+1 The response describes how the method changes (Points earned):
o the method begins counting mystery numbers starting at the given parameter instead of starting at 1

AP Computer Science A Page 71 of 133


Scoring Guide

Unit 4 FRQ

13. Directions: SHOW ALL YOUR WORK. REMEMBER THAT PROGRAM SEGMENTS ARE TO BE
WRITTEN IN JAVA.

Notes:

• Assume that the classes listed in the Java Quick Reference have been imported where appropriate.
• Unless otherwise noted in the question, assume that parameters in method calls are not null and
that methods are called only when their preconditions are satisfied.
• In writing solutions for each question, you may use any of the accessible methods that are listed in
classes defined in that question. Writing significant amounts of code that can be replaced by a call to
one of these methods will not receive full credit.

4. This question involves simulating the behavior of a dog, based on boolean values obtained by the
getResponse method in the following DogAnalysis class. You will write one method in the class.

public class DogAnalysis


{
/** Returns true if the dog sat on command and returns false otherwise
*/
public static boolean getResponse()
{ /* implementation not shown */ }

/** Returns the number of times the dog was asked to sit, as described
in part (a)
* Precondition
Precondition: n >= 1
*/
public static int numUntilObedient(int n)
{ /* to be implemented in part (a) */ }

// There may be variables and methods that are not shown.


}

(a) Write the method numUntilObedient, which simulates repeatedly asking the dog to sit until the dog sits
on command n times in a row. The numUntilObedient method returns the number of times the dog was
commanded to sit before the dog obeyed the command n times in a row.

The helper method getResponse simulates the dog’s response to the sit command. It returns true if the
dog sat on command and returns false otherwise.

For example, if n is 3 and the values returned from getResponse are true, true, false, true,
false, true, true, and true, the numUntilObedient method should return 8 since the dog
obeyed the command on the , , and calls to getResponse.

Complete method numUntilObedient.

Page 72 of 133 AP Computer Science A


Scoring Guide

Unit 4 FRQ

/** Returns the number of times the dog was asked to sit, as described in
part (a)
* Precondition
Precondition: n >= 1
*/
public static int numUntilObedient(int n)

(b) A programmer wants to modify the DogAnalysis class so that the numUntilObedient method is
given a value that represents the maximum number of times the dog should be commanded to sit. The method
would return true if the dog sat n times in a row within that maximum number of attempts and would return
false otherwise.

Write a description of how you would change the method in the DogAnalysis class in order to support this
modification. Do not write the program code for this change.

Make sure to include the following in your response.

• Identify any new or modified variables or methods.


• Describe, for each new or revised variable or method, how it would change or be implemented,
including visibility and type.

Part A – numUntilObedient

Select a point value to view scoring criteria, solutions, and/or examples and to score the response. +1 indicates a point
earned and -1 indicates a general or question-specific penalty.

+1 [Skill 3.C] Iterates until desired number of successes in a row

Responses can still earn the point even if they:

· return early inside the loop

· calculate successes in a row incorrectly

Responses will not earn the point if they:

· test the count of all attempts instead of the count of successes in a row

· use an incorrect comparison

+1 [Skill 3.A] Calls

Responses can still earn the point even if they:

· do not use a loop

· do not use or store the return value

Responses will not earn the point if they call incorrectly

+1 [Skill 3.C] Maintains counter of all commands given (in the context of a loop)

AP Computer Science A Page 73 of 133


Scoring Guide

Unit 4 FRQ

Responses can still earn the point even if they:

· call incorrectly

· terminate the loop under incorrect conditions

Responses will not earn the point if they:

· do not initialize or increment count

· return early inside the loop

· omit or double-count some calls to

+1 [Skill 3.C] Updates count of successes in a row based on value returned by

Responses can still earn the point even if they:

· call incorrectly

· do not have a loop

· terminate the loop under incorrect conditions

· omit or double-count some calls to

Responses will not earn the point if they:

· do not initialize number of successes in a row

· never increment successes or never reset to zero

· use the wrong condition to determine whether to increment or reset to zero

+1 [Skill 3.C] Returns count of attempts

Responses can still earn the point even if they calculate count incorrectly

Responses will not earn the point if they return the number of successes in a row instead of count of commands given

-1 (w) Extraneous code that causes side-effect (e.g., printing to output, incorrect precondition check)

-1 (x) Local variables used but none declared

-1 (t) Do not initialize both counters

Canonical Solution:

Page 74 of 133 AP Computer Science A


Scoring Guide

Unit 4 FRQ

0 1 2 3 4 5

Total number of points earned (minus penalties) is equal to 5.

+1 Iterates until desired number of successes in a row (Points earned)


+1 Calls (Points earned)
+1 Maintains counter of all commands given (in the context of a loop) (Points earned)
+1 Updates count of successes in a row based on value returned by (Points earned)
+1 Returns count of attempts (Points earned)
-1 [penalty] (w) Extraneous code that causes side-effect (e.g., printing to output, incorrect precondition
check) (General penalties)
-1 [penalty] (x) Local variables used but none declared (General penalties)
-1 [penalty] (t) Do not initialize both counters (General penalties)

Canonical Solution:

AP Computer Science A Page 75 of 133


Scoring Guide

Unit 4 FRQ

Part B – Change to numUntilObedient

Select a point value to view scoring criteria, solutions, and/or examples and to score the response. +1 indicates a point
earned and -1 indicates a general or question-specific penalty.

+1 [Skill 3.B] The response identifies changes to the method header:

· would return a instead of an OR there would need to be an additional


parameter or new non-local variable

+1 [Skill 3.C] The response describes how the method changes:

· the new variable is compared to the count of all commands, either as a loop condition or to determine the return value

Responses can still earn the point even if they:

o do not specify a change to the header

o do not limit the number of times that is called

Responses only earn the point if all described components are plausible, accurate, and consistent as related to the problem

0 1 2

Total number of points earned (minus penalties) is equal to 2.

+1 The response identifies changes to the method header (Points earned):


o would return a instead of an OR there would need to be an
additional parameter or new non-local variable

Page 76 of 133 AP Computer Science A


Scoring Guide

Unit 4 FRQ

+1 The response describes how the method changes (Points earned):


o the new variable is compared to the count of all commands, either as a loop condition or to determine
the return value

AP Computer Science A Page 77 of 133


Scoring Guide

Unit 4 FRQ

14. SHOW ALL YOUR WORK. REMEMBER THAT PROGRAM SEGMENTS ARE TO BE WRITTEN IN JAVA.

Assume that the classes listed in the Java Quick Reference have been imported where appropriate.
Unless otherwise noted in the question, assume that parameters in method calls are not null and that methods
are called only when their preconditions are satisfied.
In writing solutions for each question, you may use any of the accessible methods that are listed in classes
defined in that question. Writing significant amounts of code that can be replaced by a call to one of these
methods will not receive full credit.

This question involves the StringManip class, which is used to perform manipulation on strings.

The class provides the removeSpaces method, whose implementation is not shown. The method takes a string and
returns a new string with spaces removed. For example, removeSpaces("hi how are you") returns
"hihowareyou". The removeSpaces method will be used in part (b).

public class StringManip


{
/** Takes a string str and returns a new string
* with all spaces removed.
*/
public static String removeSpaces(String str)
{ /* implementation not shown */ }

/** Takes a string str and returns a new string


* with the characters reversed, as described in part (a).
*/
public static String reverseString(String str)
{ /* to be implemented in part (a) */ }

/** Determines whether str is a palindrome and prints a message


* indicating the result, as described in part (b).
* Precondition: str contains only lowercase letters and spaces.
*/
public static void palindromeChecker(String str)
{ /* to be implemented in part (b) */ }
}

(a) Write method reverseString, which takes a string str and returns a new string with the characters in str in
reverse order. For example, reverseString("ABCDE") should return "EDCBA".

Complete the reverseString method below by assigning the reversed string to result.

/** Takes a string str and returns a new string


* with the characters reversed.
*/

Page 78 of 133 AP Computer Science A


Scoring Guide

Unit 4 FRQ

public static String reverseString(String str)


{
String result = "";
return result;
}

For this question, let a palindrome be defined as a string that, when spaces are removed, reads the same forward and
backward. For example, "race car" and "taco cat" are palindromes. You will write method
palindromeChecker, which determines whether a string is a palindrome and prints a message indicating the result.
Examples of the intended behavior of the method are shown in the following table.

Method Call Printed Message


palindromeChecker("taco cat") taco cat is a palindrome
palindromeChecker("laid on no dial") laid on no dial is a palindrome
palindromeChecker("level up") level up is not a palindrome

(b) Write method palindromeChecker below. Assume that reverseString works as specified, regardless of
what you wrote in part (a). You must use reverseString and removeSpaces appropriately to receive full credit.
Your implementation must conform to the examples in the table.

/** Determines whether str is a palindrome and prints a message


* indicating the result, as described in part (b).
* Precondition: str contains only lowercase letters and spaces.
*/
public static void palindromeChecker(String str)

Part A - reverseString method (4 points)

Points earned:

+1 [Skill 3.A] Examines an individual character in using substring or another appropriate method

+1 [Skill 3.C] Iterates over each character in without bounds error

+1 [Skill 3.C] Uses concatenation to build a new string from characters in

+1 [Skill 3.C] Assigns correct reversed string to to be returned

General Penalties:

-1 (w) Extraneous code that causes side-effect (e.g., printing to output, incorrect precondition check)

Canonical Solution:

AP Computer Science A Page 79 of 133


Scoring Guide

Unit 4 FRQ

Alternate Canonical Solution:

= 0; j--) Line 5: { Line 6: result += str.substring(j, j + 1); Line 7: } Line 8: return result; Line 9: }">

0 1 2 3 4

Total number of points earned (minus penalties) is equal to 4.

+1 Examines an individual character in using substring or another appropriate method ( Points


Earned )
+1 Iterates over each character in without bounds error ( Points Earned )
+1 Uses concatenation to build a new string from characters in ( Points Earned )
+1 Assigns correct reversed string to to be returned ( Points Earned )
-1 (w) Extraneous code that causes side-effect (e.g., printing to output, incorrect precondition check)
(General Penalties)

Canonical Solution:

Page 80 of 133 AP Computer Science A


Scoring Guide

Unit 4 FRQ

Alternate Canonical Solution:

= 0; j--) Line 5: { Line 6: result += str.substring(j, j + 1); Line 7: } Line 8: return result; Line 9: }">

Part B - palindromeChecker method (5 points)

Points Earned:

+1 [Skill 3.A] Removes spaces from the string to be compared but retains spaces for the string used in printed message

Response earn this point if it…

· reverses the string before removing the spaces

+1 [Skill 3.A] Calls to obtain a reversed string

Response earn this point if it…

· reverses the string before removing the spaces

Response earns this point, but incurs general penalty x below if it...

· uses a local variable for the reversed string, but does not declare it.

+1 [Skill 3.A] Compares a string to its reverse using or another appropriate method

+1 [Skill 3.C] Uses a condition statement to print one message when is a palindrome and print another message
otherwise

+1 [Skill 3.C] Prints messages in specified format

General Penalties:

-1 (w) Extraneous code that causes side-effect (e.g., printing to output, incorrect precondition check)

-1 (x) Local variables used but none declared

-1 (z) Void method or constructor that returns a value

Canonical Solution:

AP Computer Science A Page 81 of 133


Scoring Guide

Unit 4 FRQ

0 1 2 3 4 5

Total number of points earned (minus penalties) is equal to 5.

+1 Removes spaces from the string to be compared but retains spaces for the string used in printed
message ( Points Earned )
+1 Calls to obtain a reversed string ( Points Earned )
+1 Compares a string to its reverse using or another appropriate method ( Points Earned )
+1 Uses a condition statement to print one message when is a palindrome and print another message
otherwise ( Points Earned )
+1 Prints messages in specified format ( Points Earned )
-1 (w) Extraneous code that causes side-effect (e.g., printing to output, incorrect precondition check)
(General Penalties)
-1 (x) Local variables used but none declared (General Penalties)
-1 (z) Void method or constructor that returns a value (General Penalties)

Canonical Solution:

Page 82 of 133 AP Computer Science A


Scoring Guide

Unit 4 FRQ

15. SHOW ALL YOUR WORK. REMEMBER THAT PROGRAM SEGMENTS ARE TO BE WRITTEN IN JAVA.

Assume that the classes listed in the Java Quick Reference have been imported where appropriate.
Unless otherwise noted in the question, assume that parameters in method calls are not null and that methods
are called only when their preconditions are satisfied.
In writing solutions for each question, you may use any of the accessible methods that are listed in classes
defined in that question. Writing significant amounts of code that can be replaced by a call to one of these
methods will not receive full credit.

The method printNums has two parameters: value and numRounds. The method will iterate for
numRounds rounds. In each round, random integers between 0 and 9, inclusive, are generated and printed on a
single line until value is generated. At that time, value is printed and the round stops. Values for the next
round are printed on the next line of output.

For example, a call to printNums(5, 4) could result in the following output. Each round stops when 5 is
printed for a total of four rounds.

325
7884465
06165
9678971145

Complete method printNums below.

public static void printNums(int value, int numRounds)

printNums method (5 points)

Points earned:

+1 [Skill 3.C] Generates numbers in a single round until is generated.

+1 [Skill 3.C] Generates the correct number of rounds (no bounds errors).

+1 [Skill 3.C] Uses nested loops to generate sequences of values for all rounds.

+1 [Skill 3.A] Generates values in the correct range.

+1 [Skill 3.A] Output is printed in the appropriate format, with each round on its own line.

Response earns this point, but incurs general penalty z below if it...

· returns a value from the method

General Penalties:

-1 (w) Extraneous code that causes side-effect (e.g., printing to output, incorrect precondition check)

-1 (x) Local variables used but none declared


-1 (z) Void method or constructor that returns a value

AP Computer Science A Page 83 of 133


Scoring Guide

Unit 4 FRQ

Canonical Solution:

0 1 2 3 4 5

Total number of points earned (minus penalties) is equal to 5.

+1 Generates numbers in a single round until is generated. ( Points earned )


+1 Generates the correct number of rounds (no bounds errors). ( Points earned )
+1 Uses nested loops to generate sequences of values for all rounds. ( Points earned )
+1 Generates values in the correct range. ( Points earned )
+1 Output is printed in the appropriate format, with each round on its own line. ( Points earned )
-1 (w) Extraneous code that causes side-effect (e.g., printing to output, incorrect precondition check)(
General Penalties )
-1 (x) Local variables used but none declared( General Penalties )
-1 (z) Void method or constructor that returns a value( General Penalties )

Canonical Solution:

Page 84 of 133 AP Computer Science A


Scoring Guide

Unit 4 FRQ

AP Computer Science A Page 85 of 133


Scoring Guide

Unit 4 FRQ

16. Directions: SHOW ALL YOUR WORK. REMEMBER THAT PROGRAM SEGMENTS ARE TO BE
WRITTEN IN JAVA.

Notes:

• Assume that the classes listed in the Java Quick Reference have been imported where appropriate.
• Unless otherwise noted in the question, assume that parameters in method calls are not null and
that methods are called only when their preconditions are satisfied.
• In writing solutions for each question, you may use any of the accessible methods that are listed in
classes defined in that question. Writing significant amounts of code that can be replaced by a call to
one of these methods will not receive full credit.

2. The PrimeNumber class contains methods used with prime numbers. You will write one method of the
PrimeNumber class.

public class PrimeNumber


{
/** Returns true if num is a prime number and false otherwise */
private static boolean isPrimeNumber(int num)
{ /* implementation not shown */ }

/** Returns the proportion of numbers between start and end, inclusive,
that are
* prime, as described in part (a)
* Precondition
Precondition: 1 < start <= end <= Integer.MAX_VALUE
*/
public static double propOfPrimes(int start, int end)
{ /* to be implemented in part (a) */ }

// There may be variables and methods that are not shown.


}

(a) Write the method propOfPrimes, which returns the proportion of numbers between start and
end, inclusive, that are prime. A helper method, isPrimeNumber, has been provided. The
isPrimeNumber method returns true if its parameter is a prime number and returns false otherwise.

For example, there are numbers between and , inclusive, and of them are prime ( , , , and ), so
the method call PrimeNumber.propOfPrimes(5, 14) returns 0.4.

You must use isPrimeNumber appropriately to receive full credit.

Complete method propOfPrimes.

/** Returns the proportion of numbers between start and end, inclusive,

Page 86 of 133 AP Computer Science A


Scoring Guide

Unit 4 FRQ

that are prime,


* as described in part (a)
* Precondition
Precondition: 1 < start <= end <= Integer.MAX_VALUE
*/
public static double propOfPrimes(int start, int end)

(b) A programmer wants to modify the PrimeNumber class so that the propOfPrimes method always
returns the proportion of numbers between and a given number, inclusive, that are prime.

Write a description of how you would change the PrimeNumber class in order to support this modification. Do
not write the program code for this change.

Make sure to include the following in your response.

• Identify any new or modified variables or methods.


• Describe, for each new or revised variable or method, how it would change or be implemented,
including visibility and type.

Part A – propOfPrimes

Select a point value to view scoring criteria, solutions, and/or examples and to score the response. +1 indicates a point
earned and -1 indicates a general or question-specific penalty.

+1 [Skill 3.C] Loops through all potential prime numbers between and , inclusive

Responses can still earn the point even if they return early inside the loop

+1 [Skill 3.A] Calls on a value between and , inclusive

Responses will not earn the point if they call incorrectly

+1 [Skill 3.C] Increments number of primes based on return value (in the context of a loop)

Responses can still earn the point even if they call incorrectly

Responses will not earn the point if they do not initialize the counter

+1 [Skill 3.C] Determines denominator for proportion calculation

Responses will not earn the point if they use an incorrectly computed denominator

+1 [Skill 3.C] Returns value representing the proportion of primes in range of to

Responses can still earn the point even if they use incorrect values for the numerator or the denominator of the proportion

Responses will not earn the point if they use integer division before casting

-1 (w) Extraneous code that causes side-effect (e.g., printing to output, incorrect precondition check)

-1 (x) Local variables used but none declared

AP Computer Science A Page 87 of 133


Scoring Guide

Unit 4 FRQ

Canonical Solution:

0 1 2 3 4 5

Total number of points earned (minus penalties) is equal to 5.

+1 Loops through all potential prime numbers between and , inclusive (Points earned)
+1 Calls on a value between and , inclusive (Points earned)
+1 Increments number of primes based on return value (in the context of a loop)
(Points earned)
+1 Determines denominator for proportion calculation (Points earned)
+1 Returns value representing the proportion of primes in range of to (Points
earned)
-1 [penalty] (w) Extraneous code that causes side-effect (e.g., printing to output, incorrect precondition
check) (General penalties)
-1 [penalty] (x) Local variables used but none declared (General penalties)

Canonical Solution:

Page 88 of 133 AP Computer Science A


Scoring Guide

Unit 4 FRQ

Part B – PrimeNumber

Select a point value to view scoring criteria, solutions, and/or examples and to score the response. +1 indicates a point
earned and -1 indicates a general or question-specific penalty.

+1 [Skill 3.B] The response identifies changes to the method header:

· would have a single parameter

Responses can still earn the point even if they:

o identify reassignment of the parameter to the value 2 inside the method without removing the parameter

o do not indicate to remove a parameter, but indicate the use of the value 2 in place of the parameter and remove all
references to the parameter from the method

+1 [Skill 3.C] The response describes how the method changes:

· the method would start the loop at 2 and end at the given parameter. The calculation of the proportion would also change
since the count of numbers examined would be one less than the given input value

Responses can still earn the point even if they do not specify a change to the method header

Responses only earn the point if all described components are plausible, accurate, and consistent as related to the problem

0 1 2

Total number of points earned (minus penalties) is equal to 2.

+1 The response identifies changes to the method header:


o would have a single parameter (Points earned)
+1 The response describes how the method changes (Points earned):
o the method would start the loop at 2 and end at the given parameter. The calculation of the proportion
would also change since the count of numbers examined would be one less than the given input value

AP Computer Science A Page 89 of 133


Scoring Guide

Unit 4 FRQ

17. Directions: SHOW ALL YOUR WORK. REMEMBER THAT PROGRAM SEGMENTS ARE TO BE
WRITTEN IN JAVA.

Notes:

• Assume that the classes listed in the Java Quick Reference have been imported where appropriate.
• Unless otherwise noted in the question, assume that parameters in method calls are not null and
that methods are called only when their preconditions are satisfied.
• In writing solutions for each question, you may use any of the accessible methods that are listed in
classes defined in that question. Writing significant amounts of code that can be replaced by a call to
one of these methods will not receive full credit.

4. The NumberProperties class contains methods used to determine various properties of numbers. You
will write one method of the NumberProperties class.

public class NumberProperties


{
/** Returns true if num is a perfect square and false otherwise */
private static boolean isSquare(int num)
{ /* implementation not shown */ }

/** Returns true if num is a perfect cube and false otherwise */


private static boolean isCube(int num)
{ /* implementation not shown */ }

/** Returns the ratio of the sum of all the perfect cubes between start
and end,
* inclusive, to the sum of all the perfect squares between start
and end, inclusive,
* as described in part (a)
* Precondition
Precondition: 1 <= start <= end <= Integer.MAX_VALUE
* There is at least one perfect square between start
and end,
* inclusive.
*/
public static double ratioOfCubeSumsToSquareSums(int start, int end)
{ /* to be implemented in part (a) */ }

// There may be variables and methods that are not shown.


}

(a) Write the method ratioOfCubeSumsToSquareSums, which returns the ratio of the sum of all perfect
cubes between start and end, inclusive, to the sum of all perfect squares between start and

Page 90 of 133 AP Computer Science A


Scoring Guide

Unit 4 FRQ

end, inclusive.

Two helper methods, isSquare and isCube, have been provided. The isSquare method returns true
if its parameter is a perfect square and returns false otherwise. The isCube method returns true if its
parameter is a perfect cube and returns false otherwise.

For example, of the numbers between and , inclusive, two are perfect cubes ( and ) and three are perfect
squares ( , , and ). The sum of the two perfect cubes is and the sum of the three perfect squares is .
The method call NumberProperties.ratioOfCubeSumsToSquareSums(5, 30) returns the ratio of
the sums 35 and 50, which is 0.7.

You must use isSquare and isCube appropriately to receive full credit. Assume that there is at least one
perfect square between start and end, inclusive.

Complete method ratioOfCubeSumsToSquareSums.

/** Returns the ratio of the sum of all the perfect cubes between start
and end, inclusive,
* to the sum of all the perfect squares between start and end,
inclusive,
* as described in part (a)
* Precondition
Precondition: 1 <= start <= end <= Integer.MAX_VALUE
* There is at least one perfect square between start and
end, inclusive.
*/
public static double ratioOfCubeSumsToSquareSums(int start, int end)

(b) A programmer wants to modify the NumberProperties class so that the


ratioOfCubeSumsToSquareSums method examines values beginning at start and continues until it
finds a given positive number of perfect squares.

Write a description of how you would change the NumberProperties class in order to support this
modification. Do not write the program code for this change.

Make sure to include the following in your response.

• Identify any new or modified variables or methods.


• Describe, for each new or revised variable or method, how it would change or be implemented,
including visibility and type.

Part A – ratioOfCubeSumsToSquareSums

Select a point value to view scoring criteria, solutions, and/or examples and to score the response. +1 indicates a point
earned and -1 indicates a general or question-specific penalty.

+1 [Skill 3.C] Loops through all numbers between and , inclusive

Responses can still earn the point even if they return early inside the loop

+1 [Skill 3.A] Calls and on a value between and , inclusive

AP Computer Science A Page 91 of 133


Scoring Guide

Unit 4 FRQ

Responses will not earn the point if they call or incorrectly

+1 [Skill 3.C] Uses and return values to guard increment of counters

Responses can still earn the point even if they:

· call or incorrectly

· use incorrect logic to guard the increment

Responses will not earn the point if they do not increment variables for the sums of squares and cubes

+1 [Skill 3.C] Sums all squares and cubes between and (algorithm)

Responses can still earn the point even if they:

· accumulate using variables that are declared as variables and susceptible to overflow

· terminate the loop under incorrect conditions

· assume that a number cannot be both a perfect cube and a perfect square

Responses will not earn the point if they:

· do not increment the sums in the context of a loop

· use incorrect logic to guard the increment

· increment sum of perfect squares or perfect cubes incorrectly

· do not initialize variables for the sums of squares and cubes

+1 [Skill 3.C] Calculates and returns proportion

Responses can still earn the point even if they calculate a return value based on incorrect counts

Responses will not earn the point if they use integer division before casting

-1 (w) Extraneous code that causes side-effect (e.g., printing to output, incorrect precondition check)

-1 (x) Local variables used but none declared

Canonical Solution:

Page 92 of 133 AP Computer Science A


Scoring Guide

Unit 4 FRQ

0 1 2 3 4 5

Total number of points earned (minus penalties) is equal to 5.

+1 Loops through all numbers between and , inclusive (Points earned)


+1 Calls and on a value between and , inclusive (Points earned)
+1 Uses and return values to guard increment of counters (Points earned)
+1 Sums all squares and cubes between and (algorithm) (Points earned)
+1 Calculates and returns proportion (Points earned)
-1 [penalty] (w) Extraneous code that causes side-effect (e.g., printing to output, incorrect precondition
check) (General penalties)
-1 [penalty] (x) Local variables used but none declared (General penalties)

Canonical Solution:

AP Computer Science A Page 93 of 133


Scoring Guide

Unit 4 FRQ

Part B – NumberProperties class updates

Select a point value to view scoring criteria, solutions, and/or examples and to score the response. +1 indicates a point
earned and -1 indicates a general or question-specific penalty.

+1 [Skill 3.B] The response identifies properties of the variable needed to support the change in the method:

· the second parameter of the method would become the number of perfect squares to include

OR

· a new variable of type (or integer) to represent the number of perfect squares to include

Responses can still earn the point even if they:

· do not mention a change to method parameters

· reuse existing parameter with new meaning

Responses will not earn the point if they:

· mention a new parameter but use an inappropriate type, e.g.,

· add a new parameter instead of replacing the existing parameter

+1 [Skill 3.C] The response describes how the method changes:

· the implementation would change to keep track of how many perfect squares have been found, and the loop would
change so that it terminates when the given number of perfect squares are found

Responses can still earn the point even if they do not specify a change to the
method header

Page 94 of 133 AP Computer Science A


Scoring Guide

Unit 4 FRQ

Responses only earn the point if all described components are plausible, accurate, and consistent as related to the problem

0 1 2

Total number of points earned (minus penalties) is equal to 2.

+1 The response identifies properties of the variable needed to support the change in the method (Points
earned):
o the second parameter of the method would become the number of perfect squares to include
OR
o a new variable of type (or integer) to represent the number of perfect squares to include
+1 The response describes how the method changes (Points earned):
o the implementation would change to keep track of how many perfect squares have been found, and the
loop would change so that it terminates when the given number of perfect squares are found

AP Computer Science A Page 95 of 133


Scoring Guide

Unit 4 FRQ

18. SHOW ALL YOUR WORK. REMEMBER THAT PROGRAM SEGMENTS ARE TO BE WRITTEN IN JAVA.

Assume that the classes listed in the Java Quick Reference have been imported where appropriate.
Unless otherwise noted in the question, assume that parameters in method calls are not null and that methods
are called only when their preconditions are satisfied.
In writing solutions for each question, you may use any of the accessible methods that are listed in classes
defined in that question. Writing significant amounts of code that can be replaced by a call to one of these
methods will not receive full credit.

This question involves objects of the Kid and Parent classes below.

public class Kid


{
/** Returns a reference to the Parent object associated
* with this Kid object
*/
public Parent getParent()
{ /* implementation not shown */ }

// Constructors and other methods not shown


}

public class Parent


{
/** Returns true if this object and other are equal
* and returns false otherwise.
*/
{ /* implementation not shown */ }

// Constructors and other methods not shown


}

The determineRelationship method appears in a class other than Kid or Parent. The
determineRelationship method takes Kid objects one and two as parameters. The intended behavior of
the method is described below.

If one and two refer to the same Kid object, the method should print "Same kid".
Regardless of whether one and two refer to the same Kid object, the method should print "Same parent"
if the Parent objects returned by getParent are equal as determined by the equals method.
If the Parent objects returned by getParent are not equal as determined by the equals method, the
method should print "Unrelated".

Complete method determineRelationship below.

public static void determineRelationship(Kid one, Kid two)

determineRelationship method (4 points)

Page 96 of 133 AP Computer Science A


Scoring Guide

Unit 4 FRQ

+1 [Skill 3.C] Determines if and refer to the same object.

+1 [Skill 3.A] Calls on and .

+1 [Skill 3.A] Calls the method on parent objects of and to determine if they have the same parent.

+1 [Skill 3.C] Prints appropriate message based on whether and have the same parent references.

Response earns this point, but incurs general penalty z below if it...

· returns a value from the method

General Penalties:

-1 (w) Extraneous code that causes side-effect (e.g., printing to output, incorrect precondition check)

-1 (x) Local variables used but none declared

-1 (z) Void method or constructor that returns a value

Canonical Solution:

Alternate Canonical Solution:

AP Computer Science A Page 97 of 133


Scoring Guide

Unit 4 FRQ

0 1 2 3 4

Total number of points earned (minus penalties) is equal to 4.

+1 Determines if and refer to the same object. (Points earned)


+1 Calls on and (Points earned)
+1 Calls the method on parent objects of and to determine if they have the same parent.
(Points earned)
+1 Prints appropriate message based on whether and have the same parent references. (Points
earned)
-1 (w) Extraneous code that causes side-effect (e.g., printing to output, incorrect precondition check)
(General Penalties)
-1 (x) Local variables used but none declared (General Penalties)
-1 (z) Void method or constructor that returns a value (General Penalties)

Canonical Solution:

Page 98 of 133 AP Computer Science A


Scoring Guide

Unit 4 FRQ

Alternate Canonical Solution:

AP Computer Science A Page 99 of 133


Scoring Guide

Unit 4 FRQ

19. SHOW ALL YOUR WORK. REMEMBER THAT PROGRAM SEGMENTS ARE TO BE WRITTEN IN
JAVA.

• Assume that the classes listed in the Java Quick Reference have been imported where appropriate.
• Unless otherwise noted in the question, assume that parameters in method calls are not null and
that methods are called only when their preconditions are satisfied.
• In writing solutions for each question, you may use any of the accessible methods that are listed in
classes defined in that question. Writing significant amounts of code that can be replaced by a call to
one of these methods will not receive full credit.

A manufacturer wants to keep track of the average of the ratings that have been submitted for an item using a
running average. The algorithm for calculating a running average differs from the standard algorithm for
calculating an average, as described in part (a).

A partial declaration of the RunningAverage class is shown below. You will write two methods of the
RunningAverage class.

public class RunningAverage


{
/** The number of ratings included in the running average. */
private int count;

/** The average of the ratings that have been entered. */


private double average;

// There are no other instance variables.

/** Creates a RunningAverage object.


* Postcondition: count is initialized to 0 and average is
* initialized to 0.0.
*/
public RunningAverage()
{ /* implementation not shown */ }

/** Updates the running average to reflect the entry of a new


* rating, as described in part (a).
*/
public void updateAverage(double newVal)
{ /* to be implemented in part (a) */ }

/** Processes num new ratings by considering them for inclusion


* in the running average and updating the running average as
* necessary. Returns an integer that represents the number of
* invalid ratings, as described in part (b).
* Precondition: num > 0
*/

Page 100 of 133 AP Computer Science A


Scoring Guide

Unit 4 FRQ

public int processNewRatings(int num)


{ /* to be implemented in part (b) */ }

/** Returns a single numeric rating. */


public double getNewRating()
{ /* implementation not shown */ }
}

(a) Write the method updateAverage, which updates the RunningAverage object to include a new
rating. To update a running average, add the new rating to a calculated total, which is the number of ratings times
the current running average. Divide the new total by the incremented count to obtain the new running average.

For example, if there are ratings with a current running average of , the calculated total is times , or
. When a fifth rating with a value of is included, the new total becomes . The new running average is
divided by , or .

Complete method updateAverage.

/** Updates the running average to reflect the entry of a new


* rating, as described in part (a).
*/
public void updateAverage(double newVal)

(b) Write the processNewRatings method, which considers num new ratings for inclusion in the running
average. A helper method, getNewRating, which returns a single rating, has been provided for you.

The running average must only be updated with ratings that are greater than or equal to zero. Ratings that are less
than 0 are considered invalid and are not included in the running average.

The processNewRatings method returns the number of invalid ratings. See the table below for three
examples of how calls to processNewRatings should work.

AP Computer Science A Page 101 of 133


Scoring Guide

Unit 4 FRQ

Ratings processNewRatings

Statement Comments

Generated Return Value

Both new ratings are


processNewRatings(2) 2.5, 4.5 0 included in the
running average.
No new ratings are
processNewRatings(1) -2.0 1 included in the
running average.

0.0,
-2.2, Two new ratings (0.0
and 3.5) are
processNewRatings(4) 2
included in the
3.5, running average.
-1.5

Complete method processNewRatings. Assume that updateAverage works as specified, regardless of


what you wrote in part (a). You must use getNewRating and updateAverage appropriately to receive
full credit.

/** Processes num new ratings by considering them for inclusion


* in the running average and updating the running average as
* necessary. Returns an integer that represents the number of
* invalid ratings, as described in part (b).
* Precondition: num > 0
*/
public int processNewRatings(int num)

Part A – updateAverage

Select a point value to view scoring criteria, solutions, and/or examples and to score the response. indicates a point
earned and indicates a general or question-specific penalty.

[Skill 3.C] Computes total and updates total and count

Responses can still earn the point even if they fail to update instance variables

[Skill 3.C] Calculates correct average

Responses can still earn the point even if the calculated total and/or count is incorrect

Page 102 of 133 AP Computer Science A


Scoring Guide

Unit 4 FRQ

Responses will not earn the point if the calculation results in a loss of precision (i.e. integer division)

[Skill 3.B] Updates instance variables ( and )

Responses can still earn the point even if they calculate or incorrectly

(w) Extraneous code that causes side-effect (e.g., printing to output, incorrect precondition check)

(x) Local variables used but none declared

(y) Destruction of persistent data (e.g., changing value referenced by parameter)

(z) Void method or constructor that returns a value

Canonical Solution:

0 1 2 3

Total number of points earned (minus penalties) is equal to 3.

Computes total and updates total and count (Points earned)


Calculates correct average (Points earned)
Updates instance variables ( and ) (Points earned)
[penalty] (w) Extraneous code that causes side-effect (e.g., printing to output, incorrect precondition
check) (General penalties)
[penalty] (x) Local variables used but none declared (General penalties)
[penalty] (y) Destruction of persistent data (e.g., changing value referenced by parameter) (General
penalties)
[penalty] (z) Void method or constructor that returns a value (General penalties)

Canonical Solution:

AP Computer Science A Page 103 of 133


Scoring Guide

Unit 4 FRQ

Part B – processNewRatings method

Select a point value to view scoring criteria, solutions, and/or examples and to score the response. indicates a point
earned and indicates a general or question-specific penalty.

[Skill 3.C] Loops times (no bounds errors)

[Skill 3.A] Calls

Responses can still earn the point even if they call more than once per iteration

Responses will not earn the point if they

· include parameters

· call on an object or class other than

[Skill 3.C] Compares a rating and

Responses can still earn the point even if the comparison with is incorrect

[Skill 3.A] Calls

Responses will not earn the point if they

· include a parameter of the incorrect type

· call on an object or class other than

[Skill 3.C] Computes number of invalid ratings and includes only appropriate ratings in the average (algorithm)

Responses will not earn the point if they

· include in the incorrect case

· reverse the direction of the comparison

· call more than once per iteration

· do not initialize counter to

· do not put the computation in the context of iteration

· include negative ratings in running average

Page 104 of 133 AP Computer Science A


Scoring Guide

Unit 4 FRQ

· return early

[Skill 3.B] Returns counted number of omitted values

Responses can still earn the point even if the returned count is incorrect

(w) Extraneous code that causes side-effect (e.g., printing to output, incorrect precondition check)

(x) Local variables used but none declared

(y) Destruction of persistent data (e.g., changing value referenced by parameter)

(z) Void method or constructor that returns a value

Canonical Solution:

= 0) Line 8: { Line 9: updateAverage(v); Line 10: } Line 11: else Line 12: { Line 13: invalid++; Line 14:} Line 15: } Line
16: return invalid; Line 17: } end code">

0 1 2 3 4 5 6

Total number of points earned (minus penalties) is equal to 6.

Loops times (no bounds errors) (Points earned)


Calls (Points earned)
Compares a rating and (Points earned)
Calls (Points earned)
Computes number of invalid ratings and includes only appropriate ratings in the average (algorithm)
(Points earned)

AP Computer Science A Page 105 of 133


Scoring Guide

Unit 4 FRQ

Returns counted number of omitted values (Points earned)


[penalty] (w) Extraneous code that causes side-effect (e.g., printing to output, incorrect precondition
check) (General penalties)
[penalty] (x) Local variables used but none declared (General penalties)
[penalty] (y) Destruction of persistent data (e.g., changing value referenced by parameter) (General
penalties)
[penalty] (z) Void method or constructor that returns a value (General penalties)

Canonical Solution:

= 0) Line 8: { Line 9: updateAverage(v); Line 10: } Line 11: else Line 12: { Line 13: invalid++; Line 14:} Line 15: } Line
16: return invalid; Line 17: } end code">

Page 106 of 133 AP Computer Science A


Scoring Guide

Unit 4 FRQ

20. Directions: SHOW ALL YOUR WORK. REMEMBER THAT PROGRAM SEGMENTS ARE TO BE
WRITTEN IN JAVA.

Notes:

• Assume that the classes listed in the Java Quick Reference have been imported where appropriate.
• Unless otherwise noted in the question, assume that parameters in method calls are not null and
that methods are called only when their preconditions are satisfied.
• In writing solutions for each question, you may use any of the accessible methods that are listed in
classes defined in that question. Writing significant amounts of code that can be replaced by a call to
one of these methods will not receive full credit.

4. This question involves analyzing integer values that are obtained using the getInt method in the following
TargetIntegers class. You will write one method in the class.

public class TargetIntegers


{
/** Returns an int from simulated user input */
public static int getInt()
{ /* implementation not shown */ }

/** Returns true if x is considered a target number; returns false


otherwise
* Some target numbers are positive and some are negative.
*/
public static boolean isTarget(int x)
{ /* implementation not shown */ }

/** Analyzes sampleSize values obtained using the getInt method, as


described
* in part (a)
* Precondition
Precondition: sampleSize is a positive even integer.
*/
public static boolean runSimulation(int sampleSize)
{ /* to be implemented in part (a) */ }

// There may be variables and methods that are not shown.


}

(a) Some integer values are considered target numbers. A helper method, isTarget, has been provided.
Method isTarget returns true if its parameter is a target number and returns false otherwise. Some
target numbers are positive, and some are negative.

AP Computer Science A Page 107 of 133


Scoring Guide

Unit 4 FRQ

Method runSimulation obtains sampleSize values using the getInt method. The method returns
true if there are more positive target values (target values that are greater than ) in the first half of the obtained
values than in the second half of the obtained values.

Complete method runSimulation. You must use getInt and isTarget appropriately in order to
receive full credit.

/** Analyzes sampleSize values obtained using the getInt method, as


described in
* part (a)
* Precondition
Precondition: sampleSize is a positive even integer.
*/
public static boolean runSimulation(int sampleSize)

(b) A programmer wants to modify the TargetIntegers class so that the number of values to be analyzed by
the runSimulation method is maintained in a variable with a value that cannot change once it is initialized.

Write a description of how you would change the TargetIntegers class in order to support this
modification. Do not write the program code for this change.

Make sure to include the following in your response.

• Identify any new or modified variables or methods.


• Describe, for each new or revised variable or method, how it would change or be implemented,
including visibility and type.

Part A – runSimulation

Select a point value to view scoring criteria, solutions, and/or examples and to score the response. +1 indicates a point
earned and -1 indicates a general or question-specific penalty.

+1 [Skill 3.C] Iterates a total of times

Responses can still earn the point even if they do not split the sample into two equal-sized parts

+1 [Skill 3.A] Calls (in the context of a loop)

Responses can still earn the point even if they do not use the return value

Responses will not earn the point if they call incorrectly

+1 [Skill 3.C] Compares input values to and calls to identify inputs to be included in counts

Responses can still earn the point even if they:

· call incorrectly

· use the comparison to select negative numbers

· do not split the sample size into two equal-sized parts

Page 108 of 133 AP Computer Science A


Scoring Guide

Unit 4 FRQ

Responses will not earn the point if they:

· do not use the return value in the comparison or call to

· call incorrectly

+1 [Skill 3.C] Maintains separate counts for each half of integers obtained

Responses can still earn the point even if they:

· call incorrectly

· do not use the return value in the conditional statement

· do not split the sample into two consecutive parts

Responses will not earn the point if they:

· do not initialize variables to store counts

· increment counts by anything other than 1

· do not partition the sample into two equal-sized parts

· select and count negative numbers

+1 [Skill 3.C] Returns based on comparison of counts

Responses can still earn the point even if they use incorrectly calculated counts in calculating the return value

-1 (w) Extraneous code that causes side-effect (e.g., printing to output, incorrect precondition check)

-1 (x) Local variables used but none declared

-1 (s) Consistent use of preceding method calls

Canonical Solution:

AP Computer Science A Page 109 of 133


Scoring Guide

Unit 4 FRQ

0 && isTarget(input)) Line 9: { Line 10: count1++; Line 11: } Line 12: } Line 13 is blank. Line 14: int count2 = 0; Line
15: for (int i = 0; i 0 && isTarget(input)) Line 20: { Line 21: count2++; Line 22: } Line 23: } Line 24 is blank. Line 25:
return (count1 > count2); Line 26: } end code ">

0 1 2 3 4 5

Total number of points earned (minus penalties) is equal to 5.

+1 Iterates a total of times (Points earned)


+1 Calls (in the context of a loop) (Points earned)
+1 Compares input values to and calls to identify inputs to be included in counts (Points
earned)
+1 Maintains separate counts for each half of integers obtained (Points earned)
+1 Returns based on comparison of counts (Points earned)
-1 [penalty] (w) Extraneous code that causes side-effect (e.g., printing to output, incorrect precondition
check) (General penalties)
-1 [penalty] (x) Local variables used but none declared (General penalties)
-1 [penalty] (s) Consistent use of preceding method calls (General penalties)

Canonical Solution:

Page 110 of 133 AP Computer Science A


Scoring Guide

Unit 4 FRQ

0 && isTarget(input)) Line 9: { Line 10: count1++; Line 11: } Line 12: } Line 13 is blank. Line 14: int count2 = 0; Line
15: for (int i = 0; i < sampleSize / 2; i++) Line 16: { Line 17: int input = getInt(); Line 18 is blank. Line 19: if (input > 0
&& isTarget(input)) Line 20: { Line 21: count2++; Line 22: } Line 23: } Line 24 is blank. Line 25: return (count1 >
count2); Line 26: } end code ">

Part B – Store number of simulations

Select a point value to view scoring criteria, solutions, and/or examples and to score the response. +1 indicates a point
earned and -1 indicates a general or question-specific penalty.

+1 [Skill 3.B] The response identifies properties of the new variable:

· or "integer"

· or "constant"

Responses can still earn the point even if they specify the variable as an instance variable

+1 [Skill 3.B] The response describes how the method changes:

· would need to change so that it has no parameters and uses the variable in place of the previous
parameter

Responses can still earn the point even if they omit

Responses only earn the point if all described components are plausible, accurate, and consistent as related to the problem

AP Computer Science A Page 111 of 133


Scoring Guide

Unit 4 FRQ

0 1 2

Total number of points earned (minus penalties) is equal to 2.

+1 The response identifies properties of the new variable (Points earned):


o or "integer"
o or "constant"
+1 The response describes how the method changes (Points earned):
· would need to change so that it has no parameters and uses the variable in place
of the previous parameter

Page 112 of 133 AP Computer Science A


Scoring Guide

Unit 4 FRQ

21. SHOW ALL YOUR WORK. REMEMBER THAT PROGRAM SEGMENTS ARE TO BE WRITTEN IN JAVA.

Assume that the classes listed in the Java Quick Reference have been imported where appropriate.
Unless otherwise noted in the question, assume that parameters in method calls are not null and that methods
are called only when their preconditions are satisfied.
In writing solutions for each question, you may use any of the accessible methods that are listed in classes
defined in that question. Writing significant amounts of code that can be replaced by a call to one of these
methods will not receive full credit.

This question involves a game that is played with multiple spinners. You will write two methods in the SpinnerGame
class below.

public class SpinnerGame


{
/** Precondition: min < max
* Simulates a spin of a spinner by returning a random integer
* between min and max, inclusive.
*/
public int spin(int min, int max)
{ /* to be implemented in part (a) */ }

/** Simulates one round of the game as described in part (b).


*/
public void playRound()
{ /* to be implemented in part (b) */ }
}

(a) The spin method simulates a spin of a fair spinner. The method returns a random integer between min and max,
inclusive. Complete the spin method below by assigning this random integer to result.

/** Precondition: min < max


* Simulates a spin of a spinner by returning a random integer
* between min and max, inclusive.
*/
public int spin(int min, int max)
{
int result;
return result;
}

In each round of the game, the player and the computer each spin a spinner. The player spins a spinner numbered 1 to
10 , inclusive, whereas the computer spins a spinner numbered 2 to 8, inclusive.

Based on the results of the spins, a message is printed in the formats shown in the examples below.

AP Computer Science A Page 113 of 133


Scoring Guide

Unit 4 FRQ

If the player obtains a higher result than the computer, the player gains a number of points equal to the positive
difference between the spins. If the computer obtains a higher result than the player, the player loses a number of points
equal to the positive difference between the spins.

In the event of a tie, the player and the computer each spin the spinner a second time. If the sum of the player’s two
spins are greater than the sum of the computer’s two spins, the player gains one point. If the sum of the computer’s two
spins are greater than the sum of the player’s two spins, the player loses one point. In the event of a tie after two spins,
the round is reported as a tie and the player’s score does not change.

Examples of the playRound method’s intended behavior are shown in the following table.

Player Spin Computer Spin Player Spin Computer Spin


Printed String
#1 #1 #2 #2
You win! 3
9 6
points
You lose.
3 7
points
You win! 1
4 4 6 2
points
You lose.
6 6 1 2
points
1 1 8 8 Tie. 0 points

(b) Complete the playRound method below. You must use the spin method appropriately in order to earn full
credit.

/** Simulates one round of the game as described in part (b).


*/
public void playRound()

Part A - spin method (2 points)

Points earned:

+1 [Skill 3.C] Determine the correct number of possible random numbers in the range.

Response earns this point, but incurs general penalty x below if it...

· creates a local variable for the number of random choices, but does not declare it.

+1 [Skill 3.A] Generates a random integer in the determined range, inclusively, and is stored in to be returned.

Response earn this point if it…

· redeclares .

Page 114 of 133 AP Computer Science A


Scoring Guide

Unit 4 FRQ

Response do not earn this point if it…

· does not appropriately cast the random number to an .

General Penalties:

-1 (w) Extraneous code that causes side-effect (e.g., printing to output, incorrect precondition check)

-1 (x) Local variables used but none declared

Canonical Solution:

0 1 2

Total number of points earned (minus penalties) is equal to 2.

+1 Determine the correct number of possible random numbers in the range. (Points earned)
+1 Generated random integer is in the determined, inclusive, and is stored in to be returned
(Points earned)
-1 (w) Extraneous code that causes side-effect (e.g., printing to output, incorrect precondition check)
(General Penalties)
-1 (x) Local variables used but none declared (General Penalties)

Canonical Solution:

Part B - playRound method (7 points)

Points earned:

+1 [Skill 3.A] Calls the method appropriately to generate first spins for the player and the computer

AP Computer Science A Page 115 of 133


Scoring Guide

Unit 4 FRQ

Response earns this point, but incurs general penalty x below if it…

· Uses local variables for the spin of player and computer without declaring them,
+1 [Skill 3.C] Checks for a tie on the first pair of spins

+1 [Skill 3.C] Reports a player win or a computer win, if appropriate, based on only the first pair of spins

+1 [Skill 3.C] Stores second spins for the player and computer so that sums are available to compare (i.e., does not
overwrite previously generated values)

Response earns the point if it…

· doesn’t call the method correctly.

Response does not earn the point if it..

· does not create new variables for the second computer and player spins. (Note that general penalty x is not incurred
in this case.)

+1 [Skill 3.C] Compares correct sums in the case of a tie based on the first pair of spins

Response earns the point if it…

uses appropriate relational operators and arithmetic expression to compare the sums even if the statement is incorrect.

+1 [Skill 3.C] Reports a player win, computer win, or tie, as appropriate, after the second pair of spins
+1 [Skill 3.A] All messages are in the specified format.

General Penalties:

-1 (w) Extraneous code that causes side-effect (e.g., printing to output, incorrect precondition check)

-1 (x) Local variables used but none declared

-1 (y) Destruction of persistent data (e.g., changing value referenced by parameter)

-1 (z) Void method or constructor that returns a value

Canonical Solution:

Page 116 of 133 AP Computer Science A


Scoring Guide

Unit 4 FRQ

computerSpin1 + Line 11: computerSpin2) Line 12: { Line 13: System.out.println("You win! 1 points"); Line 14: } Line
15: else if (computerSpin1 + computerSpin2 > Line 16: playerSpin1 + playerSpin2) Line 17: { Line 18:
System.out.println("You lose. -1 points"); Line 19: } Line 20: else Line 21: { Line 22: System.out.println("Tie. 0
points!"); Line 23: } Line 24: } Line 25: else if (result > 0) Line 26: { Line 27: System.out.println("You win! " + result +
Line 28: " points"); Line 29: } Line 30: else Line 31: { Line 32: System.out.println("You lose. " + result + Line 33: "
points"); Line 34: } Line 35: }">

0 1 2 3 4 5 6 7

Total number of points earned (minus penalties) is equal to 7.

+1 Calls the method appropriately to generate first spins for the player and the computer (Points
earned)
+1 Checks for a tie on the first pair of spins (Points earned)
+1 Reports a player win or a computer win, if appropriate, based on only the first pair of spins (Points
earned)
+1 Stores second spins for the player and computer so that sums are available to compare (i.e., does not
overwrite previously generated values) (Points earned)
+1 Compares correct sums in the case of a tie based on the first pair of spins (Points earned)
+1 Reports a player win, computer win, or tie, as appropriate, after the second pair of spins (Points

AP Computer Science A Page 117 of 133


Scoring Guide

Unit 4 FRQ

earned)
+1 All messages are in the specified format. (Points earned)
-1 (w) Extraneous code that causes side-effect (e.g., printing to output, incorrect precondition check)
(General Penalties)
-1 (x) Local variables used but none declared (General Penalties)
-1 (y) Destruction of persistent data (e.g., changing value referenced by parameter) (General Penalties)
-1 (z) Void method or constructor that returns a value (General Penalties)

Canonical Solution:

computerSpin1 + Line 11: computerSpin2) Line 12: { Line 13: System.out.println("You win! 1 points"); Line 14: } Line
15: else if (computerSpin1 + computerSpin2 > Line 16: playerSpin1 + playerSpin2) Line 17: { Line 18:
System.out.println("You lose. -1 points"); Line 19: } Line 20: else Line 21: { Line 22: System.out.println("Tie. 0
points!"); Line 23: } Line 24: } Line 25: else if (result > 0) Line 26: { Line 27: System.out.println("You win! " + result +
Line 28: " points"); Line 29: } Line 30: else Line 31: { Line 32: System.out.println("You lose. " + result + Line 33: "
points"); Line 34: } Line 35: }">

Page 118 of 133 AP Computer Science A


Scoring Guide

Unit 4 FRQ

22. SHOW ALL YOUR WORK. REMEMBER THAT PROGRAM SEGMENTS ARE TO BE WRITTEN IN JAVA.

• Assume that the classes listed in the Java Quick Reference have been imported where appropriate.
• Unless otherwise noted in the question, assume that parameters in method calls are not null and
that methods are called only when their preconditions are satisfied.
• In writing solutions for each question, you may use any of the accessible methods that are listed in
classes defined in that question. Writing significant amounts of code that can be replaced by a call to
one of these methods will not receive full credit.

This question involves the WordMatch class, which stores a secret string and provides methods that compare
other strings to the secret string. You will write two methods in the 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)
{
/* implementation not shown */
}

/** 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-breaker that are described in part (b).
* Precondition: guess1 and guess2 contain all lowercase letters.
* guess1 is not the same as guess2.
*/
public String findBetterGuess(String guess1, String guess2)
{ /* to be implemented in part (b) */ }
}

(a) Write the WordMatch method scoreGuess. To determine the score to be returned,
scoreGuess finds the number of times that guess occurs as a substring of secret and then multiplies
that number by the square of the length of guess. Occurrences of guess may overlap within secret.

Assume that the length of guess is less than or equal to the length of secret and that guess is not an

AP Computer Science A Page 119 of 133


Scoring Guide

Unit 4 FRQ

empty string.

The following examples show declarations of a WordMatch object. The tables show the outcomes of some
possible calls to the scoreGuess method.

WordMatch game = new WordMatch("mississippi");

Score Calculation:

(Number of
Number of

Return Value of
Substring
Value of guess Substring
Occurrences) x
game.scoreGuess(guess)

Occurrences
(Square of the

Length of guess
guess)

"i" 4 * 1 * 1 = 4 4
"iss" 2 * 3 * 3 = 18 18
"issipp" 1 * 6 * 6 = 36 36
1 * 11 * 11 =
"mississippi" 121
121

WordMatch game = new WordMatch("aaaabb");

Page 120 of 133 AP Computer Science A


Scoring Guide

Unit 4 FRQ

Score Calculation:

(Number of
Number of

Return Value of
Value of Substring Occurrences)
Substring
guess x
game.scoreGuess(guess)

Occurrences
(Square of the

Length of guess
guess)

"a" 4 * 1 * 1 = 4 4
"aa" 3 * 2 * 2 = 12 12
"aaa" 2 * 3 * 3 = 18 18
"aabb" 1 * 4 * 4 = 16 16
"c" 0 * 1 * 1 = 0 0

Complete the scoreGuess method.

/** Returns a score for guess, as described in part (a).


* Precondition: 0 < guess.length() <= secret.length()
*/
public int scoreGuess(String guess)

(b) Write the WordMatch method findBetterGuess, which returns the better guess of its two String
parameters, guess1 and guess2. If the scoreGuess method returns different values for guess1 and
guess2, then the guess with the higher score is returned. If the scoreGuess method returns the same value
for guess1 and guess2, then the alphabetically greater guess is returned.

The following example shows a declaration of a WordMatch object and the outcomes of some possible calls to
the scoreGuess and findBetterGuess methods.

WordMatch game = new WordMatch("concatenation");

AP Computer Science A Page 121 of 133


Scoring Guide

Unit 4 FRQ

Return

Method Call Explanation

Value

9 1 * 3 * 3
game.scoreGuess("ten");

36 1 * 6 * 6
game.scoreGuess("nation");

Since scoreGuess returns 36 for

game.findBetterGuess("ten",
"nation"
"nation"); "nation" and 9 for "ten", the
guess with the greater score, "nation",
is returned.

9 1 * 3 * 3
game.scoreGuess("con");

9 1 * 3 * 3
game.scoreGuess("cat");
Since scoreGuess returns 9 for both
game.findBetterGuess("con",
"con" "con" and "cat", the alphabetically
"cat");
greater guess, "con", is returned.

Complete method findBetterGuess.

Assume that scoreGuess works as specified, regardless of what you wrote in part (a). You must use
scoreGuess appropriately to receive full credit.

/** Returns the better of two guesses, as determined by scoreGuess


* and the rules for a tie-breaker that are described in part (b).
* Precondition: guess1 and guess2 contain all lowercase letters.
* guess1 is not the same as guess2.
*/
public String findBetterGuess(String guess1, String guess2)

Part A – scoreGuess

Select a point value to view scoring criteria, solutions, and/or examples and to score the response. indicates a point
earned and indicates a general or question-specific penalty.

Page 122 of 133 AP Computer Science A


Scoring Guide

Unit 4 FRQ

[Skill 3.C] Compares to a substring of

Responses can still earn the point even if they only call

Responses will not earn the point if they use instead of

[Skill 3.A] Uses a substring of with correct length for comparison with guess

Responses can still earn the point even if they

· only call

· use instead of

[Skill 3.C] Loops through all necessary substrings of (no bounds errors)

Responses will not earn the point if they skip overlapping occurrences

[Skill 3.C] Counts number of identified occurrences of within (in the context of a condition involving
both secret and guess)

Responses can still earn the point even if they

· initialize count incorrectly or not at all

· identify occurrences incorrectly

[Skill 3.C] Calculates and returns correct final score (algorithm)

Responses will not earn the point if they

· initialize count incorrectly or not at all

· fail to use a loop

· fail to compare to multiple substrings of

· count the same matching substring more than once

· use a changed or incorrect length when computing the score

(w) Extraneous code that causes side-effect (e.g., printing to output, incorrect precondition check)

(x) Local variables used but none declared

(y) Destruction of persistent data (e.g., changing value referenced by parameter)

Canonical Solution:

AP Computer Science A Page 123 of 133


Scoring Guide

Unit 4 FRQ

0 1 2 3 4 5

Total number of points earned (minus penalties) is equal to 5.

Compares to a substring of (Points Earned)


Uses a substring of with correct length for comparison with guess (Points Earned)
Loops through all necessary substrings of (no bounds errors) (Points Earned)
Counts number of identified occurrences of within (in the context of a condition
involving both secret and guess) (Points Earned)
Calculates and returns correct final score (algorithm) (Points Earned)
[penalty] (w) Extraneous code that causes side-effect (e.g., printing to output, incorrect precondition
check) (General Penalties)
[penalty] (x) Local variables used but none declared (General Penalties)
[penalty] (y) Destruction of persistent data (e.g., changing value referenced by parameter) (General
Penalties)

Canonical Solution:

Page 124 of 133 AP Computer Science A


Scoring Guide

Unit 4 FRQ

Part B – findBetterGuess method

Select a point value to view scoring criteria, solutions, and/or examples and to score the response. indicates a point
earned and indicates a general or question-specific penalty.

[Skill 3.A] Calls to get scores for and

Responses will not earn the point if they

· fail to include parameters in the method calls

· call the method on an object or class other than

[Skill 3.C] Compares the scores

Responses will not earn the point if they

· only compare using or

· fail to use the result of the comparison in a conditional statement

[Skill 3.C] Determines which of and is alphabetically greater

Responses can still earn the point even if they reverse the comparison

Responses will not earn the point if they

· reimplement incorrectly

· use result of as if

[Skill 3.B] Returns the identified or (algorithm)

Responses can still earn the point even if they

· call incorrectly

AP Computer Science A Page 125 of 133


Scoring Guide

Unit 4 FRQ

· compare strings incorrectly

Responses will not earn the point if they

· reverse a comparison

· omit either comparison

· fail to return a guess in some case

(w) Extraneous code that causes side-effect (e.g., printing to output, incorrect precondition check)

(x) Local variables used but none declared

(y) Destruction of persistent data (e.g., changing value referenced by parameter)

Canonical Solution:

scoreGuess(guess2)) Line 4: { Line 5: return guess1; Line 6: } Line 7: if (scoreGuess(guess2) > scoreGuess(guess1)) Line
8: { Line 9: return guess2; Line 10: } Line 11: if (guess1.compareTo(guess2) > 0) Line 12: { Line 13: return guess1; Line
14:} Line 15: return guess2; Line 16: } end code">

0 1 2 3 4

Total number of points earned (minus penalties) is equal to 4.

Calls to get scores for and (Points Earned)


Compares the scores (Points Earned)
Determines which of and is alphabetically greater (Points Earned)
Returns the identified or (algorithm) (Points Earned)

Page 126 of 133 AP Computer Science A


Scoring Guide

Unit 4 FRQ

[penalty] (w) Extraneous code that causes side-effect (e.g., printing to output, incorrect precondition
check) (General Penalties)
[penalty] (x) Local variables used but none declared (General Penalties)
[penalty] (y) Destruction of persistent data (e.g., changing value referenced by parameter) (General
Penalties)

Canonical Solution:

scoreGuess(guess2)) Line 4: { Line 5: return guess1; Line 6: } Line 7: if (scoreGuess(guess2) > scoreGuess(guess1)) Line
8: { Line 9: return guess2; Line 10: } Line 11: if (guess1.compareTo(guess2) > 0) Line 12: { Line 13: return guess1; Line
14:} Line 15: return guess2; Line 16: } end code">

AP Computer Science A Page 127 of 133


Scoring Guide

Unit 4 FRQ

23. Directions: SHOW ALL YOUR WORK. REMEMBER THAT PROGRAM SEGMENTS ARE TO BE
WRITTEN IN JAVA.

Notes:

• Assume that the classes listed in the Java Quick Reference have been imported where appropriate.
• Unless otherwise noted in the question, assume that parameters in method calls are not null and
that methods are called only when their preconditions are satisfied.
• In writing solutions for each question, you may use any of the accessible methods that are listed in
classes defined in that question. Writing significant amounts of code that can be replaced by a call to
one of these methods will not receive full credit.

2. This question involves analyzing words that are generated using the getWord method in the following
WordTester class. You will write one method in the class.

public class WordTester


{
/** Returns a generated word consisting of one or more letters */
public static String getWord()
{ /* implementation not shown */ }

/** Determines whether fewer than percent of n words examined start


with
* firstLetter and are less than maxLength characters, as described
in
* part (a)
* Precondition
Precondition: firstLetter.length() = 1, maxLength > 0
*/
public static boolean wordChecker(String firstLetter,
int maxLength, int n)
{ /* to be implemented in part (a) */ }

// There may be variables and other methods that are not shown.
}

(a) Method wordChecker examines n words that are generated by calling the getWord method
repeatedly. The wordChecker method returns true if fewer than percent of the generated words meet
both of the following criteria and returns false otherwise.

• The word begins with firstLetter.


• The length of the word is less than or equal to maxLength.

Complete method wordChecker.

Page 128 of 133 AP Computer Science A


Scoring Guide

Unit 4 FRQ

/** Determines whether fewer than 10 percent of n words examined start


with
* firstLetter and are less than maxLength characters, as described in
* part (a)
* Precondition
Precondition: firstLetter.length() = 1, maxLength > 0
*/
public static boolean wordChecker(String firstLetter,
int maxLength, int n)

(b) A programmer wants to modify the WordTester class so that in the wordChecker method, the
percentage checked for can vary between method calls. For example, in one call to wordChecker, the method
might check whether fewer than percent of the words examined start with the letter "I", and in another call
to wordChecker, the method might check whether fewer than percent of the words examined start with the
letter "J". The programmer wants to implement this change without making any changes to the signature of the
wordChecker method or overloading wordChecker.

Write a description of how you would change the WordTester class in order to support this modification. Do
not write the program code for this change.

Make sure to include the following in your response.

• Identify any new or modified variables or methods.


• Describe, for each new or revised variable or method, how it would change or be implemented,
including visibility and type.

Part A – wordChecker

Select a point value to view scoring criteria, solutions, and/or examples and to score the response. +1 indicates a point
earned and -1 indicates a general or question-specific penalty.

+1 [Skill 3.C] Iterates times

Responses can still earn the point even if they inappropriately return inside the loop

+1 [Skill 3.A] Uses return value

Responses will not earn the point if they call incorrectly

+1 [Skill 3.C] Uses and return values along with parameters to determine whether return
value meets criteria

Responses can still earn the point even if they:

· call incorrectly

· compare using less than, or less than or equal to

Responses will not earn the point if they:

· use instead of

AP Computer Science A Page 129 of 133


Scoring Guide

Unit 4 FRQ

· call incorrectly

· use incorrect logic to guard the increment

· have multiple calls to within the loop

+1 [Skill 3.C] Increments count under appropriate conditions (in the context of a loop)

Responses can still earn the point even if they use incorrect logic to guard the increment

Responses will not earn the point if they:

· do not initialize count

· do not use a value returned by to guard the update

+1 [Skill 3.C] Returns a based on a comparison of the calculated proportion and a value ( )

Responses can still earn the point even if they:

· accumulate count incorrectly

· return incorrect based on calculated proportion

· compare the calculated proportion incorrectly

Responses will not earn the point if they:

· calculate the proportion incorrectly based on count and

· use integer division inappropriately

· early return inside loop

-1 (w) Extraneous code that causes side-effect (e.g., printing to output, incorrect precondition check)

-1 (x) Local variables used but none declared

Canonical Solution:

Page 130 of 133 AP Computer Science A


Scoring Guide

Unit 4 FRQ

0 1 2 3 4 5

Total number of points earned (minus penalties) is equal to 5.

+1 Iterates times (Points earned)


+1 Uses return value (Points earned)
+1 Uses and return values along with parameters to determine whether
return value meets criteria (Points earned)
+1 Increments count under appropriate conditions (in the context of a loop) (Points earned)
+1 Returns a based on a comparison of the calculated proportion and a value ( ) (Points
earned)
-1 [penalty] (w) Extraneous code that causes side-effect (e.g., printing to output, incorrect precondition
check) (General penalties)
-1 [penalty] (x) Local variables used but none declared (General penalties)

Canonical Solution:

AP Computer Science A Page 131 of 133


Scoring Guide

Unit 4 FRQ

Part B – WordTester change criteria

Select a point value to view scoring criteria, solutions, and/or examples and to score the response. +1 indicates a point
earned and -1 indicates a general or question-specific penalty.

+1 [Skill 3.B] The response identifies properties of the new variable:

· or "decimal" or or "integer"

· not local to a method

Responses can still earn the point even if they:

o specify the variable as an instance variable

o do not describe a variable or identify a type, but describe an appropriate identified value as generated only once during
the method call, randomly or from user input

Responses will not earn the point if they describe a change to the method header

+1 [Skill 3.B] The response describes how the method changes:

· would need to change so that the percentage calculated in the return statement uses the new variable
instead of 0.1

Responses can still earn the point even if they describe a change to the method header

Responses only earn the point if all described components are plausible, accurate, and consistent as related to the problem

0 1 2

Page 132 of 133 AP Computer Science A


Scoring Guide

Unit 4 FRQ

Total number of points earned (minus penalties) is equal to 2.

+1 The response identifies properties of the new variable (Points earned):


o or "decimal" or or "integer"
o not local to a method
+1 The response describes how the method changes (Points earned):
o would need to change so that the percentage calculated in the return statement uses the
new variable instead of 0.1

AP Computer Science A Page 133 of 133

You might also like