Dog Walking, Signed Text, Tournament, Puzzle

Apr 3, 2026

All files

summarize_document

This document contains Free-Response Questions from the 2016 AP® Computer Science A exam. It covers several programming concepts and class implementations in Java.


Section 1: LogMessage and SystemLog Classes

This section focuses on processing log messages.

LogMessage Class

  • Purpose: Represents a single log message with a machineId and a description.
  • Constructor LogMessage(String message):
    • Parses a log message string (format: machineId:description).
    • Initializes the machineId and description instance variables.
    • Assumes the input message is a valid log message with exactly one colon and no leading/trailing spaces around the colon.
  • Method containsWord(String keyword):
    • Determines if the description properly contains the given keyword.
    • Conditions for proper containment:
      1. The keyword must be a substring of the description.
      2. The keyword must be at the beginning of the description OR immediately preceded by a space.
      3. The keyword must be at the end of the description OR immediately followed by a space.
    • Examples:
      • "error on /dev/disk disk" properly contains "disk".
      • "error on / dev/disk" does not properly contain "disk" (space before "disk").

SystemLog Class

  • Purpose: Manages a list of LogMessage objects.
  • Instance Variable: private List<LogMessage> messageList;
  • Method removeMessages(String keyword):
    • Removes all LogMessage objects from messageList whose descriptions properly contain the given keyword.
    • Returns: A List<LogMessage> containing the removed entries, in their original order.
    • Side Effect: The messageList is modified to contain only the entries that did not properly contain the keyword, maintaining their original relative order.
    • If no messages contain the keyword, an empty list is returned, and messageList remains unchanged.

Section 2: Crossword Puzzle Grid

This section deals with creating and labeling a crossword puzzle grid.

Crossword Puzzle Grid Rules

  • Definition: A 2D rectangular array of black and white squares.
  • Labeling Rule: A white square is labeled with a positive number if:
    • It is white, AND
    • (It does not have a white square immediately above it OR it does not have a white square immediately to its left OR both).
  • Labeling Order: Labeled squares are numbered consecutively starting from 1, in row-major order.

Square Class

  • Purpose: Represents an individual square in the crossword grid.
  • Constructor Square(boolean isBlack, int num):
    • Initializes a square.
    • isBlack: true if the square is black, false otherwise.
    • num: The number assigned to the square (positive if labeled, 0 if not).

Crossword Class

  • Purpose: Represents the entire crossword puzzle grid.
  • Instance Variable: private Square[][] puzzle; (stores Square objects).
  • Constructor Crossword(boolean[][] blackSquares):
    • Initializes the puzzle grid based on the blackSquares input.
    • Dimensions of puzzle match blackSquares.
    • Each Square object is created with the correct color (isBlack based on blackSquares[r][c]).
    • Squares are labeled according to the crossword labeling rule using the toBeLabeled method.
    • Labeled squares get a positive number; unlabeled squares get 0.
  • Method toBeLabeled(int r, int c, boolean[][] blackSquares):
    • A helper method to determine if a square at (r, c) should be labeled.
    • Returns true if the square meets the labeling criteria (white and meets adjacency rule), false otherwise.
    • Uses the blackSquares array to check the color of the current square and its neighbors (above and left).

Section 3: RandomStringChooser and RandomLetterChooser Classes

This section involves classes for randomly selecting strings.

RandomStringChooser Class

  • Purpose: Selects strings from a given array randomly, making each string unavailable after selection.
  • Constructor RandomStringChooser(String[] wordArray):
    • Initializes the chooser with an array of strings.
    • All strings are initially available.
    • The original wordArray parameter should not be modified.
  • Method getNext():
    • Returns a randomly chosen string from the available strings.
    • The returned string becomes unavailable for future calls.
    • If no strings are available, returns the string "NONE".
  • Instance Variables: Must be private.

RandomLetterChooser Class

  • Purpose: A subclass of RandomStringChooser that specifically handles strings composed of letters.
  • Constructor RandomLetterChooser(String str):
    • Initializes the chooser using a given string str.
    • Precondition: str contains only letters.
    • Must utilize the getSingleLetters helper method to convert the input string into an array of single-letter strings.
    • Calls the superclass constructor (RandomStringChooser) with the array of single-letter strings.
  • Helper Method getSingleLetters(String str):
    • A static method (implementation not shown in detail) that takes a string and returns an array where each element is a single-character string corresponding to a character in the input string.
    • Example: getSingleLetters("cat") returns {"c", "a", "t"}.

Section 4: StringFormatter Class

This section focuses on formatting a list of words into a string of a specified length.

Formatting Rules

  1. Input: A List<String> wordList (at least two words, letters only) and a target formattedLen.
  2. Spaces: Spaces are inserted into the gaps between words.
  3. Basic Gap Width: The minimum number of spaces to be placed in each gap, calculated to distribute spaces as evenly as possible.
    • Basic Gap Width = (formattedLen - totalLetters) / numberOfGaps
  4. Leftover Spaces: Any remaining spaces after distributing the basic gap width.
    • Leftover Spaces = (formattedLen - totalLetters) % numberOfGaps
  5. Distribution: Leftover spaces are distributed one by one into the gaps from left to right.

StringFormatter Methods

  • totalLetters(List<String> wordList):
    • Calculates and returns the sum of the lengths of all strings in wordList.
  • basicGapWidth(List<String> wordList, int formattedLen):
    • Calculates and returns the basic gap width using totalLetters and the number of gaps (which is wordList.size() - 1).
  • leftoverSpaces(List<String> wordList, int formattedLen):
    • Calculates and returns the number of leftover spaces (using the modulo operator). (Implementation provided).
  • format(List<String> wordList, int formattedLen):
    • Constructs and returns the final formatted string.
    • It uses basicGapWidth and leftoverSpaces to determine the exact number of spaces between each word.
    • The words maintain their original order.
    • Spaces are added to gaps from left to right, including the basic width plus any leftover spaces assigned to that gap.




This document contains the 2013 AP® Computer Science A Scoring Guidelines and Canonical Solutions for several questions, along with general scoring guidelines and information about The College Board. The content focuses on evaluating student code for specific programming tasks.

Question 2: TokenPass

This question assesses the ability to implement a game mechanic involving distributing tokens among players.

Part (a): TokenPass Constructor (4 points)

  • Intent: To create a TokenPass object and correctly initialize its game state.
  • Key Requirements:
    • Create an instance variable board as an integer array of size playerCount.
    • Generate a random number between 1 and 10 (inclusive) and another random number between 0 and playerCount - 1 (inclusive).
    • Initialize all entries in the board array with the first computed random value.
    • Initialize the currentPlayer instance variable with the second computed random value.

Part (b): distributeCurrentPlayerTokens Method (5 points)

  • Intent: To distribute tokens from the currentPlayer's position to subsequent positions in the board array.
  • Key Requirements:
    • Use the initial value of board[currentPlayer] to determine the number of tokens to distribute.
    • Increment at least one board entry within a loop.
    • Start the token distribution at the correct board entry (the one after currentPlayer).
    • If tokens remain after reaching the end of the board, distribute the next token to position 0.
    • Ensure that after distribution, the token count at each position in the board is correct.

Question-Specific Penalties

  • -2 (v): Consistently using an incorrect array name instead of board.
  • -1 (y): Destroying persistent data (e.g., modifying currentPlayer inappropriately).
  • -1 (z): Attempting to return a value from a void method.

Canonical Solution (Illustrative Code)

The provided code demonstrates a valid implementation for the constructor and the distributeCurrentPlayerTokens method, using modulo arithmetic for circular distribution.

Question 2: Download Manager (Implied by getDownloadInfo and updateDownloads)

This section details scoring for methods related to managing download information.

Part (a): getDownloadInfo Method (4 points)

  • Intent: To search a download list for a requested title and return the corresponding DownloadInfo object if found.
  • Key Requirements:
    • Access all necessary entries in downloadList without causing bounds errors.
    • Correctly identify and return the matching entry if it exists.
    • Call the getTitle() method on a DownloadInfo object from the downloadList.
    • Check for equality between the title from the list object and the title parameter using a String equality check (e.g., .equals()).
    • Return a reference to the matching object if found, or null if not found. An early return point is not awarded.

Part (b): updateDownloads Method (5 points)

  • Intent: To update the downloadList with information from a list of titles.
  • Key Requirements:
    • Access all entries in the titles list without bounds errors.
    • Call getDownloadInfo(title) to check if a title from the titles list exists in downloadList.
    • Increment the count in the matching DownloadInfo object if the title is found.
    • If the title is not found, construct a new DownloadInfo object with the correct information. (Note: Incrementing at the time of construction is not awarded).
    • Add the newly constructed object to the end of downloadList if the title was not found. (Note: Adding more than once is not awarded).

Question-Specific Penalties

  • -1 (g): Using getLength()/getSize() for ArrayList size.
  • -2 (v): Consistently using an incorrect array name instead of downloadList or titles.
  • -1 (z): Attempting to return a value from a void method.

Canonical Solution (Illustrative Code)

The provided code shows how to iterate through downloadList to find a matching title and how to iterate through titles to either increment an existing download or add a new one.

Question 3: JumpingCritter (GridWorld)

This question pertains to implementing a JumpingCritter within the GridWorld simulation environment.

Part (a): getEmptyLocations Method (5 points)

  • Intent: To create and return an ArrayList<Location> containing all empty locations within the grid.
  • Key Requirements:
    • Declare and construct an empty ArrayList<Location>.
    • Access all locations in the grid without bounds errors.
    • Identify empty locations within a loop.
    • Create a new Location object for each grid cell.
    • Determine if the created location is empty (i.e., contains null).
    • Include all identified empty locations in the constructed ArrayList exactly once.
    • Return the constructed ArrayList (code must have examined the grid).

Part (b): JumpingCritter Class (4 points)

  • Intent: To define a JumpingCritter that extends Critter and jumps to a randomly selected empty location.
  • Key Requirements:
    • Declare JumpingCritter extending Critter.
    • Override the getMoveLocations() method.
    • The getMoveLocations() method should return an ArrayList of empty locations obtained using GridWorldUtilities.getEmptyLocations(getGrid()).
    • The selectMoveLocation method (implicitly required for the critter to move) must handle the null location case correctly (when no empty locations exist).
    • The selectMoveLocation method must handle the random location selection correctly by overriding getMoveLocations.

Question-Specific Penalties

  • -1 (s): Causing an inappropriate state change in the world (e.g., modifying the grid or other actors unintentionally).

Canonical Solution (Illustrative Code)

The provided code includes a static getEmptyLocations method and a JumpingCritter class with an overridden getMoveLocations method and a selectMoveLocation method that handles random selection and the null case.

Question 4: SkyView

This question involves processing and analyzing scan data for a sky view.

Part (a): SkyView Constructor (5 points)

  • Intent: To construct a SkyView object from a 1D array of scan data.
  • Key Requirements:
    • Construct a correctly-sized 2D array of doubles (view) and assign it to an instance variable.
    • Initialize at least one element of view with a value from the scanned array within a loop.
    • Place consecutive values from scanned into at least one row of view in their original order.
    • Place consecutive values from scanned into at least one row of view in reverse order.
    • Ensure all elements of view have correct values upon exit, without bounds errors on view or scanned.

Part (b): getAverage Method (4 points)

  • Intent: To compute and return the average of a rectangular section of the view array, specified by parameters.
  • Key Requirements:
    • Declare and initialize a double accumulator (e.g., sum).
    • Add all and only the necessary values from view to the accumulator, without bounds errors.
    • Compute the average of the specified rectangular section (sum divided by count).
    • Return the computed average (the computation must involve the view array).

Question-Specific Penalties

  • -2 (v): Consistently using an incorrect array name instead of view or scanned.

Canonical Solution (Illustrative Code)

The provided code demonstrates a constructor that populates the 2D view array, alternating between forward and reverse order for rows, and a getAverage method that iterates through a specified rectangular sub-region to calculate the average.

General Scoring Guidelines

These guidelines apply across all questions and provide a framework for awarding points and applying penalties.

Key Principles

  • Rubric Precedence: The question-specific assessment rubric takes precedence over general guidelines.
  • Penalty Application: Penalty points can only be deducted from points earned within a specific part of a question.
  • Non-Negative Scores: No part of a question (a, b, c) can have a negative point total.
  • Single Penalty Assessment: A given penalty can only be assessed once per question, even if it occurs multiple times or in different parts.

Specific Penalties

  • (w) Extraneous code causing side effects (e.g., output, failure to compile).
  • (x) Local variables used but not declared.
  • (y) Destruction of persistent data (e.g., changing a parameter's referenced value).
  • (z) Void method or constructor returning a value.
  • o Extraneous code with no side effect (e.g., precondition check).
  • o Spelling/case discrepancies if ambiguity exists.
  • o Local variable not declared (if others are declared).
  • o private or public qualifier on a local variable.
  • o Missing public qualifier on class/constructor header.
  • o Keyword used as an identifier.
  • o Common mathematical symbols used as operators.
  • o = instead of == and vice versa.
  • o Array/collection access confusion ([] vs. get).
  • o length/size confusion for collections/arrays.
  • o Extraneous [] when referencing an entire array.
  • o [i, j] instead of [i][j].
  • o Extraneous size in array declaration (e.g., int [size] nums = new int [size];).
  • o Missing ; if majority are present and indentation is clear.
  • o Missing {} if indentation is clear and braces are used elsewhere.
  • o Missing () on parameter-less method/constructor invocations.
  • o Missing () around if or while conditions.

"No Penalty" Clarification

  • Spelling and case discrepancies for identifiers are considered "No Penalty" only if the correction can be unambiguously inferred from context (e.g., "ArayList" vs. "ArrayList"). If context does not allow clear inference (e.g., mistaking a class name for an object name), a penalty may apply.

The College Board Information

  • The College Board is a non-profit organization focused on connecting students to college success.
  • It offers programs like the SAT® and Advanced Placement (AP) Program.
  • The document includes trademarks and copyright information for The College Board and its programs.



AP® Computer Science A 2014 General Scoring Guidelines

This document outlines the scoring guidelines for the AP Computer Science A exam in 2014, providing a framework for evaluating student responses to free-response questions.

Core Scoring Principles

  • Rubric Precedence: The question-specific assessment rubric is the primary scoring tool and always takes precedence.
  • Penalty Application: Penalty points can only be deducted from parts of a question that have already earned credit according to the rubric.
  • No Negative Scores: No part of a question (a, b, c) can have a negative point total.
  • Single Assessment of Penalties: A specific penalty can only be assessed once per question, even if the error occurs multiple times or in different parts of the question.

General Penalty Categories

These are common errors that may incur penalty points.

  • (w) Extraneous code with side effects: Code that causes unintended consequences, such as writing to output or failing to compile.
  • (x) Local variables used but not declared: Using a local variable without declaring it first.
  • (y) Destruction of persistent data: Modifying the value referenced by a parameter, thus altering the original data.
  • (z) Void method or constructor returning a value: Attempting to return a value from a method or constructor declared as void.

Minor Errors (Often No Penalty)

These are less severe errors that may not result in a penalty if the intent is clear.

  • Extraneous code with no side effect (e.g., precondition checks).
  • Spelling/case discrepancies in identifiers if the correction is unambiguous from context.

    For example, "ArayList" instead of "ArrayList" is acceptable. However, using a class name like "Bug" instead of an object name "bug" is not unambiguously inferable.

  • Local variables not declared, provided other variables are declared and the code is otherwise functional.
  • private or public qualifiers on local variables.
  • Missing public qualifier on a class or constructor header.
  • Keywords used as identifiers.
  • Common mathematical symbols used as operators (e.g., x for multiplication, . for division).
  • Using = instead of == for comparison, and vice versa.
  • Array/collection access confusion (e.g., [] vs. .get()).
  • length/size confusion for arrays, Strings, Lists, or ArrayLists (with or without parentheses).
  • Extraneous [] when referencing an entire array.
  • Incorrect multi-dimensional array indexing (e.g., [i, j] instead of [i][j]).
  • Extraneous size in array declaration (e.g., int [size] nums = new int [size];).
  • Missing semicolon (;) if the majority are present and indentation clearly conveys intent.
  • Missing curly braces ({}) if indentation clearly conveys intent and they are used elsewhere.
  • Missing parentheses () on parameter-less method or constructor invocations.
  • Parentheses () around if or while conditions.

Question 1: Word Scramble

This question involves two parts: scrambling a single word and modifying a list of words based on the scrambling logic.

Part (a): scrambleWord Method

  • Intent: To scramble a given word by swapping all letter pairs that begin with 'A'.
  • Scoring Breakdown:
    • +1: Accesses all letters in the word from left to right without bounds errors.
    • +1: Identifies at least one letter pair where 'A' is followed by a non-'A' character.
    • +1: Reverses the identified pair ('A' and the next character) when constructing the result string.
    • +1: Constructs the correct result string. A point is lost if any letters are swapped more than once. Minor loop bounds errors are acceptable.
    • +1: Returns the constructed scrambled string.

Part (b): scrambleOrRemove Method

  • Intent: To modify a list of words by replacing each word with its scrambled version (using scrambleWord) and removing any words that remain unchanged after scrambling.
  • Scoring Breakdown:
    • +1: Accesses all words in the wordList without bounds errors.
    • +1: Calls the scrambleWord method with a word from the list as a parameter.
    • +1: Correctly identifies words that were unchanged by the scrambling process.
    • +1: On exit, the list contains only the words that were changed by scrambling, maintaining their original relative order. Minor loop bounds errors are acceptable.

Canonical Solution Example (scrambleWord and scrambleOrRemove)

public static String scrambleWord (String word) {
    String result = ""; // Assuming result is initialized
    int current = 0;
    while (current < word.length() - 1) {
        if (word.substring(current, current + 1).equals("A") &&
            !word.substring(current + 1, current + 2).equals("A")) {
            result += word.substring(current + 1, current + 2);
            result += "A";
            current += 2;
        } else {
            result += word.substring(current, current + 1);
            current++;
        }
    }
    if (current < word.length()) {
        result += word.substring(current);
    }
    return result;
}

public static void scrambleOrRemove (List<String> wordList) {
    int index = 0;
    while (index < wordList.size()) {
        String word = wordList.get(index);
        String scrambled = scrambleWord(word);
        if (word.equals(scrambled)) {
            wordList.remove(index);
        } else {
            wordList.set(index, scrambled);
            index++;
        }
    }
}

Question 3: Seating Chart

This question focuses on creating and modifying a 2D array representing a seating chart.

Part (a): SeatingChart Constructor

  • Intent: To initialize a SeatingChart object using a list of students, and specified rows and columns.
  • Scoring Breakdown:
    • +1: Correctly declares and initializes the seats 2D array (Student[][] seats = new Student[rows][cols]; or equivalent).
    • +1: Accesses all elements of the input studentList without bounds errors.
    • +1: Accesses all necessary elements of the seats array without bounds errors. A point is lost if access is not in column-major order (as shown in the canonical solution).
    • +1: Assigns at least one value from studentList to an element in the seats array.
    • +1: On exit, all elements of the seats array have the correct values assigned. Minor loop bounds errors are acceptable.

Part (b): removeAbsentStudents Method

  • Intent: To remove students from the seating chart who have more absences than a specified limit and return the count of removed students.
  • Scoring Breakdown:
    • +1: Accesses all elements of the seats array without bounds errors.
    • +1: Calls the getAbsenceCount() method on a Student object. A point is lost if the null case (empty seat) is not handled correctly.
    • +1: Assigns null to seats array elements where the occupying student's absence count exceeds allowedAbsences. A point is lost if the seats array element is modified in other cases.
    • +1: Computes and returns the correct number of students removed.

Question-Specific Penalties

  • -2 (v): Consistently uses an incorrect array name (e.g., students instead of seats or studentList).

Canonical Solution Example (SeatingChart constructor and removeAbsentStudents)

// Constructor (Column-major order example)
public SeatingChart(List<Student> studentList, int rows, int cols) {
    seats = new Student[rows][cols];
    int studentIndex = 0;
    for (int col = 0; col < cols; col++) {
        for (int row = 0; row < rows; row++) {
            if (studentIndex < studentList.size()) {
                seats[row][col] = studentList.get(studentIndex);
                studentIndex++;
            }
        }
    }
}

// Alternative Constructor (Iterating through students)
public SeatingChart(List<Student> studentList, int rows, int cols) {
    seats = new Student[rows][cols];
    int row = 0;
    int col = 0;
    for (Student student : studentList) {
        seats[row][col] = student;
        row++;
        if (row == rows) {
            row = 0;
            col++;
        }
    }
}


// removeAbsentStudents method
public int removeAbsentStudents(int allowedAbsences) {
    int count = 0;
    for (int row = 0; row < seats.length; row++) {
        for (int col = 0; col < seats[0].length; col++) {
            if (seats[row][col] != null && seats[row][col].getAbsenceCount() > allowedAbsences) {
                seats[row][col] = null;
                count++;
            }
        }
    }
    return count;
}

Question 4: Trio Class

This question involves implementing a Trio class that represents a combination of a sandwich, salad, and drink, adhering to a MenuItem interface.

  • Intent: To define an implementation of the MenuItem interface that consists of a sandwich, salad, and drink, calculating its name and price.
  • Scoring Breakdown:
    • +1: Declares the class as public class Trio implements MenuItem.
    • +1: Declares appropriate private instance variables (e.g., Sandwich sandwich;, Salad salad;, Drink drink;).
    • +2: Implements the constructor correctly:
      • +1: public Trio(Sandwich sandwich, Salad salad, Drink drink) signature.
      • +1: Initializes the instance variables using the provided parameters.
    • +1: Implements the interface methods getName() and getPrice().
    • +1: Constructs the correct name string (e.g., "SandwichName/SaladName/DrinkName Trio") and makes it available for return in getName().
    • +1: Returns the constructed name string in the getName() method.
    • +1: Computes the correct price. The price is the sum of the two most expensive items, or all three if they are equal.
    • +1: Returns the computed price in the getPrice() method.

Question-Specific Penalties

  • -0: Missing or extra spaces in the name string "trio" do not incur a penalty.
  • -1 (w): An extraneous default constructor that causes a side effect.

Canonical Solution Example (Trio class)

// Approach 1: Calculate name and price on demand
public class Trio implements MenuItem {
    private Sandwich sandwich;
    private Salad salad;
    private Drink drink;

    public Trio(Sandwich s, Salad sal, Drink d) {
        sandwich = s;
        salad = sal;
        drink = d;
    }

    public String getName() {
        return sandwich.getName() + "/" + salad.getName() + "/" + drink.getName() + " Trio";
    }

    public double getPrice() {
        double sandwichPrice = sandwich.getPrice();
        double saladPrice = salad.getPrice();
        double drinkPrice = drink.getPrice();

        if (sandwichPrice <= saladPrice && sandwichPrice <= drinkPrice) {
            return saladPrice + drinkPrice; // Sandwich is cheapest
        } else if (saladPrice <= sandwichPrice && saladPrice <= drinkPrice) {
            return sandwichPrice + drinkPrice; // Salad is cheapest
        } else {
            return sandwichPrice + saladPrice; // Drink is cheapest
        }
    }
}

// Approach 2: Calculate and store name and price in constructor
public class Trio implements MenuItem {
    private String name;
    private double price;

    public Trio(Sandwich s, Salad sal, Drink d) {
        double sandwichPrice = s.getPrice();
        double saladPrice = sal.getPrice();
        double drinkPrice = d.getPrice();

        if (sandwichPrice <= saladPrice && sandwichPrice <= drinkPrice) {
            price = saladPrice + drinkPrice;
        } else if (saladPrice <= sandwichPrice && saladPrice <= drinkPrice) {
            price = sandwichPrice + drinkPrice;
        } else {
            price = sandwichPrice + saladPrice;
        }
        name = s.getName() + "/" + sal.getName() + "/" + d.getName() + " Trio";
    }

    public String getName() {
        return name;
    }

    public double getPrice() {
        return price;
    }
}

Question 5: Director Class (Actor Extension)

This question involves extending the Rock class to create a Director class with specific behaviors related to color alternation and instructing neighbors.

  • Intent: To define a Director class that extends Rock. It alternates between red and green colors. If its color is green when it acts, it causes all its neighbors to turn right 90 degrees.
  • Scoring Breakdown:
    • +1: Declares the class as public class Director extends Rock.
    • +2: Implements the constructor:
      • +1: Director() constructor signature. An empty body is acceptable; point lost if extraneous code causes side effects.
      • +1: Sets the initial color to Color.RED using setColor() or super(Color.RED).
    • +1: Alternates the color correctly in the act() method (red to green, green to red). A point is lost for an incorrect act() method header.
    • +1: Instructs other actors to turn if and only if the Director's color is green at the beginning of the act() method execution.
    • +1: Uses getGrid() to obtain the grid for finding neighbors.
    • +1: Identifies all neighbors or neighboring locations correctly.
    • +1: Accesses all identified actors or locations without bounds errors.
    • +1: Calls setDirection() with the appropriate parameter (actor.getDirection() + Location.RIGHT) on all identified neighbors.

Canonical Solution Example (Director class)

public class Director extends Rock {

    public Director() {
        // Empty body is okay, initial color set by super or setColor
        super(Color.RED); // Or setColor(Color.RED);
    }

    public void act() {
        if (getColor().equals(Color.GREEN)) {
            // If color is green, instruct neighbors and then turn red
            ArrayList<Actor> neighbors = getGrid().getNeighbors(getLocation());
            for (Actor actor : neighbors) {
                actor.setDirection(actor.getDirection() + Location.RIGHT);
            }
            setColor(Color.RED);
        } else {
            // If color is red, turn green
            setColor(Color.GREEN);
        }
    }
}



Summary of Provided Content

This document contains a collection of Java programming questions and code snippets, likely from a computer science exam or practice material. The questions cover various aspects of Java programming, including class definitions, method implementation, array manipulation, string processing, object-oriented programming concepts (inheritance, constructors), and basic control flow (loops, conditional statements).


Section 1: WordPlay Class and Execution Analysis

  • Class Definition: The WordPlay class has a String instance variable word and methods to initialize (WordPlay(String w)), update (update(String first) and update(String first, String second)), and retrieve (getWord()) the word.
  • Method Overloading: The class demonstrates method overloading with two update methods having different parameter lists.
  • Code Execution Analysis:
    • A WordPlay object wp is initialized with "bandana".
    • wp.update("d", "tie"); is called. This update method finds the index of "d" in "bandana" (which is 2) and concatenates it with "tie", resulting in word becoming "2tie".
    • wp.update("scarf"); is called. This update method prepends "scarf" to the current word ("2tie"), resulting in word becoming "scarf2tie".
    • System.out.println(wp.getWord()); prints the final value of word.
  • Output: The printed output is "scarf2tie".
  • Note: Option (E) in the original question incorrectly states that the class doesn't compile due to two update methods; method overloading is a valid Java feature.

Section 2: BallGame Class - Simulating Throws and Calculating Averages

  • Class Structure: The BallGame class is designed to simulate a ball-throwing game. It contains two static methods: ballThrow() and averageThrow().
  • ballThrow() Method:
    • Purpose: Simulates a single throw and returns a score.
    • Scores: Possible return values are 10, 20, 30, 40, or 50.
    • Randomness: Each score has an equal probability of being returned.
    • Implementation Detail: Requires generating a random number and mapping it to one of the scores.
  • averageThrow(int numThrows, int minScore) Method:
    • Purpose: Simulates numThrows throws and calculates the average score of throws that exceed minScore.
    • Precondition: numThrows > 0.
    • Logic:
      • Iterates numThrows times, calling ballThrow() in each iteration.
      • Keeps track of the sum of scores greater than minScore and the count of such scores.
      • If no scores are greater than minScore, returns 0.0.
      • Otherwise, returns the calculated average (sum / count).
    • Example: averageThrow(3, 10) would average scores from throws that are greater than 10.

Section 3: SecretWord and TopSecretWord Classes - String Transformation

  • SecretWord Class:
    • Stores an original string.
    • Has a constructor SecretWord(String word).
    • Provides getOriginal() to retrieve the original string.
    • Has a transformWord() method that returns a scrambled version of the original string, leaving the original unchanged. The exact scrambling logic is not shown but implies a permutation of characters.
  • TopSecretWord Class:
    • Inheritance: It is a subclass of SecretWord.
    • Extended Transformation: It further transforms the scrambled string returned by SecretWord.transformWord().
    • Transformation Rules:
      • If the scrambled string's length is even: Replace the first half with " ".
      • If the scrambled string's length is odd: Replace the second half (including the middle character if length is odd) with " *** ".
    • checkLength() Method: Returns true if the final transformed string's length is greater than 5, false otherwise.
  • Sample Execution: Demonstrates how TopSecretWord modifies the scrambled string based on length parity.

Section 4: ArrayChecker Class - Inversions in Arrays

  • Concept: An inversion in an array numbers is a pair (numbers[j], numbers[k]) where numbers[j] > numbers[k] and j < k.
  • ArrayChecker Class: Contains methods to find and analyze inversions.
  • allInversions(int[] numbers) Method:
    • Purpose: Returns a list of integers representing all inversion pairs.
    • Output Format: The two values of each inversion pair appear adjacently in the list (e.g., [larger1, smaller1, larger2, smaller2, ...]). The order of pairs in the list does not matter.
    • Precondition: numbers.length >= 2 and no duplicate values.
    • Example: For {-3, 4, 2, 7, 1, 6}, inversions are (4, 2), (4, 1), (2, 1), (7, 1), (7, 6). The list could be [4, 2, 4, 1, 2, 1, 7, 1, 7, 6].
  • valueWithMostInversions(int[] numbers) Method:
    • Purpose: Returns the integer value from the original array that participates in the most inversion pairs.
    • Precondition: At least one inversion pair exists.
    • Tie-breaking: If multiple values have the maximum number of inversions, any one can be returned.
    • Helper Method: countOccur(ArrayList<Integer> nums, int value) is provided to count occurrences of a value in a list.
    • Logic: Likely involves calling allInversions first, then iterating through the original numbers, using countOccur on the inversion list to find the maximum count.

Section 5: TreasureMap Class - 2D Array Game Map

  • Classes Involved:
    • Treasure: Represents a treasure with a random number of gold coins (getGold()).
    • Location: Represents coordinates (row, col) on the map.
    • TreasureMap: Represents the game map using a 2D array Treasure[][] map.
  • TreasureMap(int r, int c, ArrayList<Location> locs) Constructor:
    • Purpose: Initializes the map instance variable.
    • Initialization: Creates a Treasure[r][c] array. Places Treasure objects only at the Locations specified in the locs ArrayList. All other map cells are null.
    • Preconditions: r > 0, c > 0, locs is valid and non-empty, locations are unique and within bounds.
  • totalGold(Location start, Location end) Method:
    • Purpose: Calculates the total gold coins within a rectangular sub-region of the map.
    • Region: Defined by start (top-left) and end (bottom-right) Location objects, inclusive.
    • Logic: Iterates through the rows from start.getRow() to end.getRow() and columns from start.getCol() to end.getCol(). For each cell, if it's not null, it calls getGold() on the Treasure object and adds it to a running total.
    • Preconditions: start and end are valid locations, start.row <= end.row, start.col <= end.col.

Section 6: Miscellaneous Java Concepts and Snippets

This section contains various multiple-choice questions testing specific Java concepts:

  • Q15: Array Comparison: Evaluates different implementations of haveSameContents to check if two arrays have the same length and elements in the same order. Implementation III is correct.
  • Q16: Loop Termination and Arithmetic: Analyzes a while loop performing subtraction and incrementing a counter. The loop terminates when x becomes less than y. The value of c represents the number of times y was subtracted from x. c = x / y (integer division). For x=102, y=5, c = 102 / 5 = 20.
  • Q17: Static Variables and Object State: Examines the behavior of a class with a static variable (maxInitialOrder) and instance variables (numOfItems). maxInitialOrder tracks the maximum initial value passed to any Container constructor. calcShippingCost() uses this static variable.
    • c1 = new Container(10): maxInitialOrder becomes 10. c1.numOfItems = 10.
    • c2 = new Container(6): maxInitialOrder remains 10. c2.numOfItems = 6.
    • c1.addItems(2): c1.numOfItems becomes 12.
    • c2.addItems(4): c2.numOfItems becomes 10.
    • c2.calcShippingCost(): Checks if c2.numOfItems (10) equals maxInitialOrder (10). It does. Returns numOfItems * 0.5 = 10 * 0.5 = 5.0.
  • Q18: Method Calls and Side Effects: Analyzes the output of code involving calls to methods (alpha, beta) that have both return values and print statements (System.out.print). Order of execution and side effects are crucial.
    • alpha(w) (where w=1): Prints 2, returns 3. Condition alpha(w) > 0 is true.
    • The || operator short-circuits, so beta(w) is not called.
    • The code inside the if block executes: System.out.print(alpha(w)).
    • alpha(w) is called again: Prints 2, returns 3.
    • Output: "22"
  • Q19: String Manipulation Edge Cases: Tests the replaceStr method. The method fails when the replacement string b is the same as the character being replaced a (e.g., replaceStr("CCD", "C", "C")). The indexOf keeps finding the same character, leading to an infinite loop.
  • Q20: Boolean Logic: Requires constructing a boolean expression that matches specific conditions: (number > 0) OR (-10 <= number <= -5). Option (D) correctly translates this using Java syntax: (-10 <= number && number <= -5) || number > 0.
  • Q21: Recursion: Traces the execution of a recursive method doSomething.
    • doSomething(10) calls doSomething(8) + 10
    • doSomething(8) calls doSomething(6) + 8
    • doSomething(6) calls doSomething(4) + 6
    • doSomething(4) calls doSomething(2) + 4
    • doSomething(2) calls doSomething(0) + 2
    • doSomething(0) returns ""
    • Result: "" + 2 + 4 + 6 + 8 + 10 = "246810"
  • Q22: 2D Array Traversal: Identifies an error in a method intended to print a 2D array in row-major order. The error is that the indices [b][a] are swapped; it should be [a][b] for row-major order. This causes ArrayIndexOutOfBoundsException if rows have different lengths.
  • Q23: Array Manipulation and Loops: Analyzes a loop that modifies an array while iterating. The loop condition k > items.length / 2 and the access items[k-1], items[k-2] suggest potential issues.
    • items.length = 6. items.length / 2 = 3.
    • Loop starts with k = 6. Condition 6 > 3 is true.
      • sum += items[5] (60). sum = 60.
      • items[5] = items[4] (50). items is now {10, 20, 30, 40, 50, 50}.
    • k becomes 5. Condition 5 > 3 is true.
      • sum += items[4] (50). sum = 110.
      • items[4] = items[3] (40). items is now {10, 20, 30, 40, 40, 50}.
    • k becomes 4. Condition 4 > 3 is true.
      • sum += items[3] (40). sum = 150.
      • items[3] = items[2] (30). items is now {10, 20, 30, 30, 40, 50}.
    • k becomes 3. Condition 3 > 3 is false. Loop ends.
    • Prints sum (150).
  • Q24: Loop Condition Modification: Compares k <= end with k < end in a for loop with k += 2. The k <= end condition includes end if it matches the pattern, while k < end excludes it. The difference depends on whether end is reachable by adding 2s starting from start.
  • Q25: Nested Loops and Output Count: Calculates the total number of times "Z" is printed by nested loops. The outer loop runs k times, and the inner loop runs k times for each outer iteration. Total prints = k * k.
  • Q26: Random Number Generation: Evaluates code segments for a method that should return "red", "blue", or "green" with equal probability (1/3 each) using Math.random().
    • Segment I: Uses integer casting. (int)(randNum * 3) produces 0, 1, or 2. Correct.
    • Segment II: Uses floating-point comparisons. randNum < 1/3.0 covers [0, 1/3), randNum < 2/3.0 covers [1/3, 2/3). The final else covers [2/3, 1). Correct.
    • Segment III: Has a logical error. The inner if condition randNum < 2 / 3.0 is checked after result might have already been set to "green" in the outer else. If randNum is, say, 0.1, it sets result = "red", then checks 0.1 < 2/3.0 (true), sets result = "blue", and returns result. If randNum is 0.7, it sets result = "green", then checks 0.7 < 2/3.0 (false), and returns result ("green"). This segment seems correct despite the nested structure.
    • All three segments appear to work correctly.
  • Q27: Selection Sort Trace: Traces the selectionSort algorithm for three passes (outer loop j=0, 1, 2).
    • Initial: [1, 6, 2, 3, 5, 1]
    • j=0: Finds min (1 at index 5), swaps elements[0] and elements[5]. Array: [1, 6, 2, 3, 5, 1]
    • j=1: Finds min (2 at index 2), swaps elements[1] and elements[2]. Array: [1, 2, 6, 3, 5, 1]
    • j=2: Finds min (1 at index 5), swaps elements[2] and elements[5]. Array: [1, 2, 1, 3, 5, 6]
    • After three passes (j=2 is the end point), the array is [1, 2, 1, 3, 5, 6]. This doesn't match any option exactly. Let's re-check the initial array and options. The initial array in the question text is missing, but the options suggest it might have started like [?, ?, 2, 3, 5, 1] or similar. Assuming the provided options are based on a specific initial state not fully shown, let's re-evaluate based on a common example. If the initial array was [6, 1, 2, 3, 5, 1]:
      • j=0: Min is 1 (index 1 or 5). Let's say index 1. Swap elements[0] and elements[1]. -> [1, 6, 2, 3, 5, 1]
      • j=1: Min is 1 (index 5). Swap elements[1] and elements[5]. -> [1, 1, 2, 3, 5, 6]
      • j=2: Min is 2 (index 2). Swap elements[2] and elements[2]. -> [1, 1, 2, 3, 5, 6] This matches option (A).
  • Q28: Sorting Order Modification: To sort in descending order, the comparison in selection sort needs to find the maximum element instead of the minimum. This requires changing < to > in the comparison line (Line 3). Line 1 controls the outer loop, Line 2 the inner loop, neither directly affects the comparison logic for finding min/max. So, only Line 3 needs modification.
  • Q29: Inheritance and Constructors: A subclass constructor (Beta) must initialize its superclass (Alpha) state. thing is in Alpha. To initialize thing to 7, the Beta constructor needs to call the Alpha constructor that takes a value. super(7); is the correct way.
  • Q30: Integer vs. Double Arithmetic: Demonstrates integer division and modulo operations.
    • r = 23, t = 10.
    • a = r % t -> 23 % 10 = 3. a becomes 3.0 (due to double assignment).
    • b = r / t -> 23 / 10 = 2 (integer division). b becomes 2.0 (due to double assignment).
    • Prints a + "+" + b -> "3.0+2.0".
  • Q31: Nested Loops for Combinations: The desired output (0,1) (0,2) (0,3) (1,2) (1,3) (2,3) suggests combinations where the inner loop variable k starts from j+1 and goes up to 3. The outer loop j goes from 0 to 3. The inner loop needs to start after j. Option (E) int k = j + 1; k < 4; k++ achieves this.
  • Q32: Array Index Out of Bounds: The code attempts to compare arr[k] with arr[k + 1]. When k reaches the last index (arr.length - 1), arr[k + 1] will access an index outside the array bounds, causing an ArrayIndexOutOfBoundsException.
  • Q33: String Manipulation (Substring): Tests different ways to swap the first and last characters of a string using substring.
    • Segment I: lastChar + middlePart + firstChar. Correct.
    • Segment II: str.substring(1) gets from index 1 to the end. This is the middle part plus the last character. Incorrect.
    • Segment III: Rebuilds the string in a complex way that seems incorrect.
  • Q34: Array Reversal: Implements reversing an array using a loop. The loop should iterate up to the middle of the array (k < values.length / 2). Inside the loop, values[k] should be swapped with values[values.length - 1 - k]. Option (A) provides the correct condition and swap index expression.
  • Q35: 2D Array Iteration and Boolean Logic: Analyzes the check method. result1 becomes true if any row is special (isSpecial(d)). result2 starts true and becomes false if any element is not incredible (!isIncredible(n)). The output true true means result1 is true AND result2 is true. This requires:
    • At least one row is special (result1 = true).
    • All elements checked are incredible (result2 remains true). Option (E) matches this: "At least one row in someArray is special, and all values in someArray are incredible."
  • Q36: Method Signature for Accessor: Asks for the correct method header to return the book title (a String) from a BookInfo object when called externally. It should be public (accessible outside) and return String. getBookName() is the standard accessor pattern. Option (B) is correct.
  • Q37: 2D Array Initialization with Pattern: The board initialization requires placing 'x' based on row and column parity.
    • Even rows (row % 2 == 0): 'x' in odd columns (col % 2 != 0).
    • Odd rows (row % 2 != 0): 'x' in even columns (col % 2 == 0). The code iterates col = col + 2. This means it's placing 'x' every other column.
    • If row is even, we need 'x' in odd columns (1, 3, 5...). The inner loop should start at col = 1.
    • If row is odd, we need 'x' in even columns (0, 2, 4...). The inner loop should start at col = 0. The provided code snippet only has one inner loop. The logic implies the starting column depends on the row. The question asks what replaces /* expr */. If the code is intended to work for both cases with a single /* expr */, it's flawed. However, if we assume the code as written is meant to be completed, and the example shows the desired outcome:
    • 4x8 board.
    • Row 0 (even): x at cols 1, 3, 5, 7. Inner loop starts at 1, increments by 2.
    • Row 1 (odd): x at cols 0, 2, 4, 6. Inner loop starts at 0, increments by 2.
    • Row 2 (even): x at cols 1, 3, 5, 7. Inner loop starts at 1, increments by 2.
    • Row 3 (odd): x at cols 0, 2, 4, 6. Inner loop starts at 0, increments by 2. The code for (int col = /* expr */; col < board[0].length; col = col + 2) needs to handle this. The simplest interpretation is that the question implies a single starting point that works given the structure. If the goal is to place 'x' in odd columns for even rows and even columns for odd rows, and the increment is always +2, the starting point must adapt. The provided snippet doesn't show how row parity affects col start. Let's re-read the prompt carefully. It asks what replaces /* expr */. The example shows x in odd columns for even rows, and even columns for odd rows. The code col = col + 2 suggests it's hitting every other column.
    • If row is even, we need col = 1, 3, 5, 7. Start = 1.
    • If row is odd, we need col = 0, 2, 4, 6. Start = 0. The code snippet doesn't show conditional logic for the start. Assuming the question implies a single expression that could be part of a larger conditional structure, or perhaps the example implies a specific row is being processed. Without more context or a conditional statement around the inner loop, it's hard to definitively choose. However, if we look at the pattern of placement:
    • Even rows: 1, 3, 5, 7...
    • Odd rows: 0, 2, 4, 6... The code col = col + 2 is fixed. The starting /* expr */ must be chosen. If the code must work for all rows with a single /* expr */, it's impossible. Let's assume the question is asking for the correct starting point for the inner loop based on the row parity. The example shows x in odd columns for even rows (start=1) and even columns for odd rows (start=0). The question is poorly phrased if it expects a single expression. Let's assume it's asking for the general logic. The most common pattern would be to check row parity inside the loop or before it. If we must pick one expression for /* expr */, and consider the example:
    • Row 0 (even): needs cols 1, 3, 5, 7. Start = 1.
    • Row 1 (odd): needs cols 0, 2, 4, 6. Start = 0. There isn't a single value for /* expr */ that works for both. The question might be flawed or require inferring a conditional structure not shown.
  • Q38: Recursion and String Concatenation: Analyzes a recursive method processWords. It concatenates words from the end of the array backwards.
    • processWords(things, 2) calls processWords(things, 3) + things[2] ("Gorilla")
    • processWords(things, 3) calls processWords(things, 4) + things[3] ("House")
    • processWords(things, 4) calls processWords(things, 5) + things[4] ("Car")
    • processWords(things, 5) returns "" (base case index >= words.length)
    • Result: "" + "Car" = "Car"
    • Then: "Car" + "House" = "CarHouse"
    • Then: "CarHouse" + "Gorilla" = "CarHouseGorilla"
    • The call was processWords(things, 2), so the final result is processWords(things, 3) + things[2] which is "CarHouse" + "Gorilla" = "CarHouseGorilla".
    • Wait, the example output is AppleGorillaHouseCar. Let's retrace.
    • processWords(things, 2) -> processWords(things, 3) + "Gorilla"
    • processWords(things, 3) -> processWords(things, 4) + "House"
    • processWords(things, 4) -> processWords(things, 5) + "Car"
    • processWords(things, 5) -> ""
    • Substituting back:
      • processWords(things, 4) returns "" + "Car" = "Car"
      • processWords(things, 3) returns "Car" + "House" = "CarHouse"
      • processWords(things, 2) returns "CarHouse" + "Gorilla" = "CarHouseGorilla"
    • The example output AppleGorillaHouseCar seems to imply the call was processWords(things, 1). Let's assume the code is correct and the example output is for a different call or there's a misunderstanding. If the call is processWords(things, 2), the output is "CarHouseGorilla". If the output AppleGorillaHouseCar is correct, the call must have been processWords(things, 1). Let's assume the code and call processWords(things, 2) are correct, then the output is "CarHouseGorilla". If the provided answer (E) is "AppleGorillaHouseCar", then the call must have been processWords(things, 1). Let's assume the question meant processWords(things, 1).
      • processWords(things, 1) -> processWords(things, 2) + "Apple"
      • processWords(things, 2) -> processWords(things, 3) + "Gorilla"
      • processWords(things, 3) -> processWords(things, 4) + "House"
      • processWords(things, 4) -> processWords(things, 5) + "Car"
      • processWords(things, 5) -> ""
      • Result: "" + "Car" = "Car"
      • Result: "Car" + "House" = "CarHouse"
      • Result: "CarHouse" + "Gorilla" = "CarHouseGorilla"
      • Result: "CarHouseGorilla" + "Apple" = "CarHouseGorillaApple"
    • This still doesn't match. Let's re-read the code: result = processWords (words, index + 1) + words [ index] ;. It appends the current word after the recursive call result.
    • processWords(things, 5) -> ""
    • processWords(things, 4) -> processWords(things, 5) + things[4] -> "" + "Car" -> "Car"
    • processWords(things, 3) -> processWords(things, 4) + things[3] -> "Car" + "House" -> "CarHouse"
    • processWords(things, 2) -> processWords(things, 3) + things[2] -> "CarHouse" + "Gorilla" -> "CarHouseGorilla"
    • processWords(things, 1) -> processWords(things, 2) + things[1] -> "CarHouseGorilla" + "Apple" -> "CarHouseGorillaApple"
    • processWords(things, 0) -> processWords(things, 1) + things[0] -> "CarHouseGorillaApple" + "Bear" -> "CarHouseGorillaAppleBear"
    • The call is processWords(things, 2). The output should be "CarHouseGorilla". The provided answer (E) "AppleGorillaHouseCar" is incorrect based on the code and call. There might be a typo in the question or the provided answer.
  • Q39: Setter Method Signature: The code item1.setPrice(6); attempts to call a method named setPrice. To change the price instance variable, the method needs to accept the new value as a parameter and assign it to price. It should be void because it modifies state, not returns a calculated value. Option (A) public void setPrice(int p) is the correct signature.
  • Q1 (Section I): Conditional Logic: Determines x and y values to print "platypus". "platypus" is printed if the else if (x + y < 30) condition is false AND the final else block is executed.
    • The first if (x > y && x % 2 == 0) must be false.
    • The else if (x + y < 30) must be false, meaning x + y >= 30.
    • Let's test options:
      • (A) x=5, y=30: x > y is false. x+y = 35 >= 30. else block runs. Prints "kangaroo".
      • (B) x=8, y=5: x > y is true. x % 2 == 0 is true. Prints "armadillo".
      • (C) x=8, y=15: x > y is false. x+y = 23 < 30. Prints "koala".
      • (D) x=10, y=15: x > y is false. x+y = 25 < 30. Prints "koala".
      • (E) x=10, y=30: x > y is false. x+y = 40 >= 30. else block runs. Prints "kangaroo".
    • None of the options result in "platypus". Re-reading the code: "platypus" is printed inside the else if block, after "koala". So, the condition x + y < 30 must be TRUE.
    • Let's re-evaluate:
      • (A) x=5, y=30: x > y false. x+y=35. 35 < 30 false. Skip else if. else runs. Prints "kangaroo".
      • (B) x=8, y=5: x > y true. x % 2 == 0 true. Prints "armadillo".
      • (C) x=8, y=15: x > y false. x+y=23. 23 < 30 true. Prints "koala" then "platypus". This is the correct option.
      • (D) x=10, y=15: x > y false. x+y=25. 25 < 30 true. Prints "koala" then "platypus". This is also a correct option.
      • (E) x=10, y=30: x > y false. x+y=40. 40 < 30 false. Skip else if. else runs. Prints "kangaroo".
    • Both (C) and (D) produce "koalaplatypus". Assuming only one answer is correct, there might be a nuance missed or a typo. Let's assume the question intends for only "platypus" to be printed, which isn't possible with this structure. If it means "platypus is printed", then both C and D work.
  • Q2 (Section I): Method Overloading: The class SomeMethods has multiple methods named testMethod with different parameter lists (overloading). The statement SomeMethods.testMethod(1234) calls the static method testMethod(int value). The implementation is not shown, but the call itself is valid. The question asks what is printed. If the method prints something, it will be printed. If it returns a value that is then printed by println, that value will be printed. Option (E) is incorrect because the class does compile. Without the implementation, we can't know the output, but the call is valid.
  • Q3 (Section I): Array Indexing Loop: Analyzes num = arr[num].
    • arr = {4, 2, 2, 3, 1}, num = 0.
    • k=0: num = arr[0] -> num = 4.
    • k=1: num = arr[4] -> num = 1.
    • k=2: num = arr[1] -> num = 2.
    • k=3: num = arr[2] -> num = 2.
    • k=4: num = arr[2] -> num = 2.
    • Loop ends. num is 2.
  • Q4 (Section I): Nested Conditionals: Determines when z is set to 20.
    • z is initialized to 0.
    • if (x < y):
      • if (x > 0): z = 10.
      • else: z = 20. (This else corresponds to x <= 0).
    • else (corresponding to x >= y): z remains 0.
    • So, z is 20 if x < y AND x <= 0. Option (C) is "Whenever x is less than y and x is not greater than 0", which is equivalent to x < y and x <= 0.
  • Q5 (Section I): Type Casting and Floating-Point Arithmetic:
    • valOne = 5.75, valTwo = 2.75.
    • x = (int) valOne + (int) valTwo; -> x = (int) 5.75 + (int) 2.75 -> x = 5 + 2 -> x = 7.
    • y = (int) (valOne + valTwo); -> y = (int) (5.75 + 2.75) -> y = (int) (8.50) -> y = 8.
    • Prints x + "" + y -> "78".
  • Q6 (Section I): while Loop Output:
    • n = 0.
    • Loop 1: n < 10 (0<10 true). n += 2 (n=2). Print "2 ".
    • Loop 2: n < 10 (2<10 true). n += 2 (n=4). Print "4 ".
    • Loop 3: n < 10 (4<10 true). n += 2 (n=6). Print "6 ".
    • Loop 4: n < 10 (6<10 true). n += 2 (n=8). Print "8 ".
    • Loop 5: n < 10 (8<10 true). n += 2 (n=10). Print "10 ".
    • Loop 6: n < 10 (10<10 false). Loop ends.
    • Output: "2 4 6 8 10 ". Option (D).
  • Q7 (Section I): Conditional Logic Equivalence: Compares conditional statements. The original code is: if (value == 7) { value++; } else { value += value; }. This means if value is 7, it increments by 1. Otherwise (if value is not 7), it doubles value. We need an equivalent structure.
    • Option (A): if (value != 7) { value += value; } else { value++; }. This matches the logic exactly.
  • Q8 (Section I): Nested Loop Output:
    • Outer loop j from 0 to 3. Inner loop k from 0 to 2. Prints j * k.
    • j=0: k=0 (00=0), k=1 (01=0), k=2 (0*2=0). Prints "0 0 0 ". Newline.
    • j=1: k=0 (10=0), k=1 (11=1), k=2 (1*2=2). Prints "0 1 2 ". Newline.
    • j=2: k=0 (20=0), k=1 (21=2), k=2 (2*2=4). Prints "0 2 4 ". Newline.
    • j=3: k=0 (30=0), k=1 (31=3), k=2 (3*2=6). Prints "0 3 6 ". Newline.
    • Output:
      0 0 0
      0 1 2
      0 2 4
      0 3 6
      
    • Option (E) matches this.
  • Q9 (Section I): Inheritance Syntax: Defines a subclass Toaster that extends Appliance. Toaster has an instance variable maxSlices. The correct syntax is public class Toaster extends Appliance { private int maxSlices; ... }. Option (D).
  • Q10 (Section I): Boolean Algebra: Simplifies (x && y) || y. Using the absorption law (A || (A && B) == A), this simplifies to y. Option (D) x || y is not equivalent. Let's recheck.
    • Truth Table: | x | y | x && y | (x && y) || y | x || y | |---|---|--------|----------------|--------| | T | T | T | T | T | | T | F | F | F | T | | F | T | F | T | T | | F | F | F | F | F |
    • The expression (x && y) || y is equivalent to y. Option (D) x || y is not always equivalent. Let's re-examine the expression (x && y) || y.
    • If y is true, the whole expression is true.
    • If y is false, the expression becomes (x && false) || false, which simplifies to false || false, which is false.
    • So, the expression evaluates to y.
    • Which option is equivalent to y? None of the options are simply y. Let's re-read the question and options.
    • Expression: (x && y) || y
    • Option (C): x && y - Not equivalent.
    • Option (D): x || y - Not equivalent (e.g., x=F, y=T -> result T, x||y is T. x=T, y=F -> result F, x||y is T).
    • Let's re-evaluate the truth table for (x && y) || y:
      • x=T, y=T: (T && T) || T = T || T = T
      • x=T, y=F: (T && F) || F = F || F = F
      • x=F, y=T: (F && T) || T = F || T = T
      • x=F, y=F: (F && F) || F = F || F = F
    • The result is TRUE if and only if y is TRUE. So the expression is equivalent to y.
    • Is there a typo in the question or options? Let's assume the question meant x || (x && y). This simplifies to x.
    • Let's assume the question meant (x || y) && y. This simplifies to y.
    • If the expression is indeed (x && y) || y, it is equivalent to y. None of the options are just y.
    • Let's reconsider the absorption law: A || (A && B) = A. The expression is y || (y && x). This simplifies to y.
    • Perhaps the question is asking which expression always evaluates to the same value as the given expression under certain conditions or if there's a simplification rule being tested.
    • Let's re-check the truth table for x || y:
      • x=T, y=T: T || T = T (Matches)
      • x=T, y=F: T || F = T (Does NOT match, original is F)
      • x=F, y=T: F || T = T (Matches)
      • x=F, y=F: F || F = F (Matches)
    • It seems there might be an error in the question or options provided, as (x && y) || y simplifies to y, and none of the options are simply y. However, if we must choose the closest or if there's a common simplification pattern tested, x || y is often related. Let's assume there's a typo and the expression was meant to be something else, or one of the options is intended to be equivalent. Given the options, and the fact that (x && y) || y is equivalent to y, and x || y is often tested alongside these, let's stick with the analysis that it simplifies to y. If forced to choose, and assuming a potential error, x || y is a common related expression.
  • Q11 (Section I): Reverse ArrayList Iteration: To print an ArrayList in reverse, the loop index k should start at the last index (names.size() - 1), continue as long as k is non-negative (k >= 0), and decrement (k--). Option (D).
  • Q12 (Section I): Recursive Summation: Calculates calc(4). This is a recursive sum: n + (n-1) + ... + 1.
    • calc(4) = calc(3) + 4
    • calc(3) = calc(2) + 3
    • calc(2) = calc(1) + 2
    • calc(1) = calc(0) + 1
    • calc(0) = 0
    • Substituting back:
      • calc(1) = 0 + 1 = 1
      • calc(2) = 1 + 2 = 3
      • calc(3) = 3 + 3 = 6
      • calc(4) = 6 + 4 = 10
    • Result is 10.
  • Q13 (Section I): 2D Array Row Access: int[][] rectangle = new int[4][5]; declares a 4x5 2D array. x = rectangle[0]; assigns the first row (which is itself a 1D array) to x. Option (A).
  • Q14 (Section I): Loop Increment for Target Value: The loop for (int v = 1; v < 20; /* missing increment */ ) needs t to be 13. t is not used in the loop. The loop variable v is not used either. This question seems incomplete or flawed as t is never modified. Assuming t was meant to be incremented or modified based on v. If we assume t should be incremented by v in each step, and we want t=13 eventually. Let's assume the loop is for (int v = 1; v < 20; v = v * C) and t += v inside.
    • If C=2 (Option C): v becomes 1, 2, 4, 8, 16. If t += v, then t = 1 + 2 + 4 + 8 + 16 = 31.
    • If C=3 (Option D): v becomes 1, 3, 9. If t += v, then t = 1 + 3 + 9 = 13. This matches. The missing increment must be v = v * 3.

This summary covers the main points and analyses of the provided Java code snippets and questions.




This document contains free-response questions from the 2013 AP Computer Science A exam, focusing on Java programming. The questions cover several distinct programming scenarios.

Question 1: Music Downloads

This question deals with managing music download information.

DownloadInfo Class

  • Stores a song's title and the number of times it has been downloaded.
  • Constructor: DownloadInfo(String title) initializes a new download with a count of 1.
  • getTitle(): Returns the song's title.
  • incrementTimesDownloaded(): Increases the download count by 1.

MusicDownloads Class

  • Manages a List<DownloadInfo> called downloadList.
  • The downloadList is guaranteed not to be null and contains no duplicate titles.

getDownloadInfo(String title) Method (Part a)

  • Purpose: To find and return a reference to a DownloadInfo object with a matching title.
  • Behavior:
    • Iterates through downloadList.
    • If a DownloadInfo object's title matches the provided title, it returns a reference to that object.
    • If no match is found, it returns null.
  • Precondition: The downloadList is not null and contains no duplicate titles.
  • Postcondition: downloadList remains unchanged.

updateDownloads(List<String> titles) Method (Part b)

  • Purpose: To update the downloadList based on a list of song titles.
  • Behavior:
    • For each title in the input titles list:
      • It first tries to find an existing DownloadInfo object using getDownloadInfo(title).
      • If found, it calls incrementTimesDownloaded() on that object.
      • If not found, it creates a new DownloadInfo object with the title and a download count of 1, and adds it to the end of the downloadList.
  • Key Rules:
    • Existing entries in downloadList maintain their order.
    • New entries are added to the end of the list in the order they first appear in the titles list.
    • For existing entries, the download count is increased by the number of times their title appeared in the titles list.
    • For new entries, the download count is initialized to the number of times their title appeared in the titles list.

Question 2: Token Pass Game

This question describes a multiplayer game involving distributing tokens on a linear board.

Game Rules

  • Players are arranged on a linear board represented by an integer array (board), where indices are player positions and values are token counts.
  • Each player starts with 1 to 10 tokens.
  • A player is randomly chosen to start their turn.
  • Turn Action:
    1. The current player collects all their tokens.
    2. Tokens are distributed one by one to players in increasing order of position, starting from the next player.
    3. If the highest position is reached during distribution, the next token goes to position 0 (circular distribution).
    4. Distribution continues until all collected tokens are distributed.
  • The currentPlayer instance variable tracks whose turn it is.

TokenPass Class

  • board: An int[] representing player positions and token counts.
  • currentPlayer: An int representing the index of the current player.

TokenPass(int playerCount) Constructor (Part a)

  • Purpose: To initialize the game board and the starting player.
  • Behavior:
    • Creates the board array with playerCount elements.
    • Fills the board array with random integers between 1 and 10 (inclusive).
    • Initializes currentPlayer to a random integer between 0 and playerCount - 1 (inclusive).

distributeCurrentPlayerTokens() Method (Part b)

  • Purpose: To implement the token distribution logic for the current player's turn.
  • Precondition: The currentPlayer has at least one token.
  • Postcondition: The currentPlayer remains unchanged.
  • Behavior:
    1. Stores the number of tokens at board[currentPlayer] into a temporary variable and sets board[currentPlayer] to 0.
    2. Iterates through the tokens to be distributed:
      • Calculates the next player's position using a circular increment: (currentPlayer + 1 + i) % playerCount, where i is the token number (starting from 0).
      • Adds one token to the calculated player's position (board[nextPlayer]++).
    3. Continues until all tokens from the temporary variable are distributed.

Question 3: GridWorld Critters

This question involves creating a new type of Critter for the GridWorld simulation.

GridWorldUtilities Class

  • Contains static utility methods for the GridWorld.

getEmptyLocations(Grid<Actor> grid) Method (Part a)

  • Purpose: To find and return a list of all empty locations in a given grid.
  • Behavior:
    • Iterates through all possible Location objects within the grid.
    • For each Location, it checks if the grid location is empty (i.e., grid.get(location) returns null).
    • If a location is empty, it's added to an ArrayList<Location>.
  • Return Value: An ArrayList<Location> containing all empty locations. Returns an empty list if no locations are empty.
  • Constraint: Each empty location should appear exactly once.

JumpingCritter Class (Part b)

  • Inheritance: Extends the Critter class.
  • Behavior:
    • act() method (implicitly inherited and not overridden): The JumpingCritter's act() method should utilize the GridWorldUtilities.getEmptyLocations() method.
    • Movement:
      1. It gets a list of all empty locations in its grid using GridWorldUtilities.getEmptyLocations(grid).
      2. If there are empty locations:
        • It randomly selects one of the empty locations.
        • It moves to the selected location.
        • It may consume actors (like bugs) at the destination location, depending on the base Critter class behavior.
      3. If there are no empty locations:
        • The JumpingCritter removes itself from the grid.
  • Constraint: Do NOT override the act() method. The solution should focus on the class structure and potentially helper methods if needed, but the core logic relies on the inherited act() method's interaction with getEmptyLocations.

Question 4: SkyView Telescope Data

This question involves reconstructing a 2D sky view from 1D telescope scan data.

Telescope Scanning Pattern

  • The telescope scans a rectangular area.
  • Data is collected into a 1D array (scanned) in "telescope order".
  • Telescope order involves scanning back and forth:
    • Row 0: Left to Right
    • Row 1: Right to Left
    • Row 2: Left to Right
    • ...and so on, alternating direction for each row.

SkyView Class

  • view: A double[][] representing the reconstructed 2D view of the sky.

SkyView(int numRows, int numCols, double[] scanned) Constructor (Part a)

  • Purpose: To initialize the SkyView object by reconstructing the 2D view from the 1D scanned data.
  • Behavior:
    1. Creates the view 2D array with dimensions numRows x numCols.
    2. Copies data from the scanned array into the view array, reordering it according to the alternating scan pattern.
    • Example Logic:
      • The first numCols elements of scanned fill view[0] from left to right.
      • The next numCols elements of scanned fill view[1] from right to left.
      • The subsequent numCols elements fill view[2] from left to right, and so on.
  • Preconditions: numRows > 0, numCols > 0, scanned.length == numRows * numCols.
  • Postcondition: view is correctly populated and oriented.

getAverage(int startRow, int endRow, int startCol, int endCol) Method (Part b)

  • Purpose: To calculate and return the average of the values within a specified rectangular sub-section of the view.
  • Behavior:
    1. Initializes sum to 0.0 and count to 0.
    2. Iterates through the rows from startRow to endRow (inclusive).
    3. Within each row, iterates through the columns from startCol to endCol (inclusive).
    4. Adds the value view[row][col] to sum.
    5. Increments count.
    6. After iterating through all elements in the section, calculates the average as sum / count.
  • Preconditions: Valid row and column ranges are provided (0 <= startRow <= endRow < view.length, 0 <= startCol <= endCol < view[0].length).
  • Return Value: The calculated average as a double.



2017 AP® Computer Science A Free-Response Questions Summary

This document contains free-response questions from the 2017 AP® Computer Science A exam, focusing on Java programming concepts. The questions cover the design and implementation of classes and methods, including string manipulation, integer digit processing, and 2D array analysis.


Question 1: Digits Class

This question involves processing the digits of a non-negative integer.

  • Digits Class:

    • Contains an ArrayList<Integer> named digitList to store the digits of a number.
    • The digits are stored in the same order as they appear in the original number.
  • Constructor Digits(int num):

    • Purpose: Initializes digitList with the digits from the input integer num.
    • Precondition: num >= 0.
    • Example:
      • new Digits(15704) results in digitList containing [1, 5, 7, 0, 4].
      • new Digits(0) results in digitList containing [0].
  • Method isStrictlyIncreasing():

    • Purpose: Returns true if the digits in digitList are in strictly increasing order; otherwise, returns false.
    • Definition of Strictly Increasing: Each element after the first must be greater than (but not equal to) the preceding element.
    • Examples:
      • new Digits(7).isStrictlyIncreasing() returns true (single digit is considered strictly increasing).
      • new Digits(1356).isStrictlyIncreasing() returns true.
      • new Digits(1336).isStrictlyIncreasing() returns false (due to repeated '3').
      • new Digits(1536).isStrictlyIncreasing() returns false ('3' is not greater than '5').
      • new Digits(65310).isStrictlyIncreasing() returns false.

Question 2: MultPractice Class

This question involves designing a class to produce multiplication practice problems.

  • StudyPractice Interface:

    • Defines two methods:
      • String getProblem(): Returns the current practice problem.
      • void nextProblem(): Advances to the next practice problem.
  • MultPractice Class:

    • Implements the StudyPractice interface.
    • Constructor MultPractice(int firstInt, int initialSecondInt):
      • firstInt: A constant integer used in all problems.
      • initialSecondInt: The starting value for the second integer in the problems.
    • getProblem() Method:
      • Returns a string in the format: "firstInt TIMES secondInt".
    • nextProblem() Method:
      • Increments the secondInt value to prepare for the next problem.
    • Behavior: Generates a sequence of multiplication problems where the first number is constant, and the second number increments sequentially.
    • Examples:
      • new MultPractice(7, 3):
        • getProblem() initially returns "7 TIMES 3".
        • Calling nextProblem() changes the internal state.
        • Subsequent getProblem() calls would return "7 TIMES 4", "7 TIMES 5", etc.
      • new MultPractice(4, 12):
        • getProblem() initially returns "4 TIMES 12".
        • p2.nextProblem(): prepares for "4 TIMES 13".
        • System.out.println(p2.getProblem()) would print "4 TIMES 13".
        • p2.nextProblem(); p2.nextProblem();: prepares for "4 TIMES 15".
        • System.out.println(p2.getProblem()) would print "4 TIMES 15".

Question 3: Phrase Class

This question involves analyzing and modifying a string stored within a class.

  • Phrase Class:

    • Maintains a phrase in an instance variable currentPhrase (a String).
    • Constructor Phrase(String p): Initializes currentPhrase with the provided string p.
    • toString() Method: Returns the currentPhrase.
  • Method findNthOccurrence(String str, int n):

    • Purpose: Returns the index of the nth occurrence of substring str within currentPhrase.
    • Returns: -1 if the nth occurrence does not exist.
    • Preconditions: str.length() > 0 and n > 0.
    • Postcondition: currentPhrase is not modified.
    • (Implementation not shown, but assumed to work correctly for other methods).
  • Method replaceNthOccurrence(String str, int n, String repl):

    • Purpose: Modifies currentPhrase by replacing the nth occurrence of str with repl.
    • Behavior: If the nth occurrence of str does not exist, currentPhrase remains unchanged.
    • Preconditions: str.length() > 0 and n > 0.
    • Requirement: Must use findNthOccurrence appropriately.
    • Examples:
      • phrase1 = new Phrase("A cat ate late."); phrase1.replaceNthOccurrence("at", 1, "rane"); -> currentPhrase becomes "A crane ate late."
      • phrase2 = new Phrase("A cat ate late."); phrase2.replaceNthOccurrence("at", 6, "xx"); -> currentPhrase remains "A cat ate late." (6th "at" doesn't exist).
      • phrase3 = new Phrase("A cat ate late."); phrase3.replaceNthOccurrence("bat", 2, "xx"); -> currentPhrase remains "A cat ate late." ("bat" not found).
      • phrase4 = new Phrase("aaaa"); phrase4.replaceNthOccurrence("aa", 1, "xx"); -> currentPhrase becomes "xxaa".
      • phrase5 = new Phrase("aaaa"); phrase5.replaceNthOccurrence("aa", 2, "bbb"); -> currentPhrase becomes "abbba".
  • Method findLastOccurrence(String str):

    • Purpose: Returns the index of the last occurrence of substring str in currentPhrase.
    • Returns: -1 if str is not found.
    • Precondition: str.length() > 0.
    • Postcondition: currentPhrase is not modified.
    • Requirement: Must use findNthOccurrence appropriately.
    • Examples:
      • phrase1 = new Phrase("A cat ate late.");
      • phrase1.findLastOccurrence("at") returns 8 (index of "at" in "late").
      • phrase1.findLastOccurrence("cat ") returns 4.
      • phrase1.findLastOccurrence("bat") returns -1.

Question 4: Successors Class

This question involves reasoning about a 2D array of integers and their positions.

  • Position Class:

    • Used to represent coordinates (row, column) within a 2D array.
    • Constructor Position(int r, int c): Creates a Position object.
    • (Instance variables, other methods not shown).
  • Successors Class: (Static methods)

  • Method findPosition(int num, int[][] intArr):

    • Purpose: Finds the location of a given integer num within a 2D integer array intArr.
    • Returns: A Position object representing the (row, column) of num, or null if num is not found in intArr.
    • Precondition: intArr contains at least one row.
    • Example: Given arr = {{5, 6, 7, 8}, {9, 10, 11, 12}, {13, 14, 15, 16}}:
      • findPosition(8, arr) returns Position(2, 1) (assuming 0-based indexing for rows/cols in the example description, though the example output shows (2,1) for value 8 which is at row 2, col 1 in the provided array). Correction based on example: The example states findPosition(8, arr) returns Position(2, 1) for the array shown, which implies the array might be structured differently or the example has a typo. The array shown is {{5, 6, 7, 8}, {9, 10, 11, 12}, {13, 14, 15, 16}}. Value 8 is at row 0, column 3. Value 14 is at row 2, column 1. Assuming the example meant findPosition(14, arr) returns Position(2, 1). Let's re-evaluate the example: "The call findPosition (8, arr) would return the Position object (2, 1) because the value 8 appears in arr at row 2 and column 1." This implies the array in the example might be different from the one depicted visually. However, if we strictly follow the visual array {{5, 6, 7, 8}, {9, 10, 11, 12}, {13, 14, 15, 16}}, then 8 is at (0, 3). If the example meant the value 14, it would be at (2, 1). We will proceed assuming the method's goal is to find the correct row/column index.
      • findPosition(17, arr) returns null.
  • Method getSuccessorArray(int[][] intArr):

    • Purpose: Creates and returns a 2D successor array.
    • Successor: The integer that is one greater than a given integer.
    • 2D Successor Array: Has the same dimensions as intArr. Each element at (r, c) in the successor array stores the Position of the successor of the integer found at (r, c) in intArr.
    • Largest Element: The position corresponding to the largest element in intArr is null in the successor array, as it has no successor within the array's range.
    • Precondition: intArr contains at least one row and contains consecutive values. Each integer may be in any position.
    • Requirement: Must use findPosition appropriately.
    • Example:
      • Given intArr containing numbers 5 through 16.
      • The successor array element corresponding to the position of 8 will contain the Position of 9.
      • The successor array element corresponding to the position of 16 (the largest) will be null.



AP® Computer Science A 2015 Free-Response Questions Summary

This document contains the free-response questions from the 2015 AP® Computer Science A exam, covering array manipulation, sparse array representation, and object-oriented design principles.


Question 1: Array Manipulation

This question focuses on processing one-dimensional and two-dimensional arrays of integers. It requires writing three static methods within a DiverseArray class.

  • arraySum(int[] arr):

    • Purpose: Calculates and returns the sum of all elements in a given one-dimensional integer array.
    • Example: For arr1 = {1, 2, 3, 4, 5}, arraySum(arr1) returns 15.
  • rowSums(int[][] arr2D):

    • Purpose: Calculates the sum of elements for each row in a two-dimensional integer array and returns these sums in a one-dimensional array.
    • Input: A two-dimensional integer array arr2D.
    • Output: A one-dimensional integer array where each element k is the sum of row k in arr2D.
    • Example: For mat1 = {{1, 2, 3, 4}, {5, 6, 7, 8}, {9, 10, 11, 12}, {13, 14, 15, 16}}, rowSums(mat1) returns {10, 26, 42, 58}. (Note: The example in the prompt shows {16, 32, 28, 20} for mat1, which implies a different mat1 than the one listed in the text. The logic is to sum each row).
  • isDiverse(int[][] arr2D):

    • Purpose: Determines if a two-dimensional array is "diverse," meaning all its rows have unique sums.
    • Input: A two-dimensional integer array arr2D.
    • Output: true if all row sums are unique, false otherwise.
    • Dependencies: Relies on rowSums (and implicitly arraySum).
    • Example:
      • mat1 (with unique row sums) returns true.
      • mat2 (where the first and last rows have the same sum) returns false.

Question 2: Hidden Word Game Logic

This question involves implementing the logic for a word guessing game. The HiddenWord class needs to store a hidden word and generate hints based on player guesses.

  • HiddenWord Class:
    • Constructor: Takes the String representing the hidden word.
    • getHint(String guess) Method:
      • Purpose: Compares a guess string with the hidden word and returns a hint string.
      • Input: A String guess (assumed to be the same length as the hidden word and contain only capital letters).
      • Output: A String hint of the same length as the guess.
      • Hint Generation Rules:
        • If guess[i] matches hiddenWord[i]: Hint character is '+'.
        • If guess[i] is present in hiddenWord but not at position i: Hint character is '*'.
        • If guess[i] is not present in hiddenWord: Hint character is '-'.
      • Important Note: Each letter in the hidden word can only be used once to match a guess letter. If a letter in the guess matches a letter in the hidden word at the correct position, that hidden word letter is "used up" and cannot be used for a '*' match.
      • Example: HiddenWord puzzle = new HiddenWord("HARPS");
        • puzzle.getHint("AAAAA") returns "-----"
        • puzzle.getHint("HELLO") returns "-*---"
        • puzzle.getHint("HEART") returns "+*--*"
        • puzzle.getHint("HARMS") returns "+*+*+"
        • puzzle.getHint("HARPS") returns "+++++"

Question 3: Sparse Array Representation

This question deals with representing and manipulating sparse arrays, which are arrays where most elements are zero. It uses a SparseArrayEntry class and a SparseArray class.

  • SparseArrayEntry Class:

    • Purpose: Represents a single non-zero element in a sparse array.
    • Instance Variables: row, col, value.
    • Constructor: SparseArrayEntry(int r, int c, int v) initializes the entry.
    • Methods: getRow(), getCol(), getValue() to access the entry's properties.
    • Immutability: Objects are immutable after construction.
  • SparseArray Class:

    • Purpose: Represents the entire sparse array using a list of SparseArrayEntry objects.
    • Instance Variables:
      • numRows: Total number of rows.
      • numCols: Total number of columns.
      • entries: A List<SparseArrayEntry> storing the non-zero elements (order is not guaranteed).
    • Constructor: SparseArray() initializes an empty sparse array.
    • Methods:
      • getNumRows(): Returns the number of rows.
      • getNumCols(): Returns the number of columns.
      • getValueAt(int row, int col):
        • Purpose: Returns the value of the element at the specified row and col.
        • Logic: Iterates through the entries list. If an entry matches the given row and col, its value is returned. If no matching entry is found, 0 is returned.
        • Precondition: 0 <= row < getNumRows() and 0 <= col < getNumCols().
      • removeColumn(int col):
        • Purpose: Removes a specified column from the sparse array.
        • Logic:
          1. Removes all SparseArrayEntry objects from entries whose column index matches the specified col.
          2. Decrements the column index of all remaining SparseArrayEntry objects whose column index is greater than col.
          3. Decrements numCols by 1.
        • Precondition: 0 <= col < getNumCols().

Question 4: Object-Oriented Design (Interfaces and Classes)

This question assesses understanding of interfaces, class implementation, and using interfaces in collections.

  • NumberGroup Interface:

    • Purpose: Defines a contract for objects that represent a group of integers.
    • Method: contains(int num): Returns true if the integer num is in the group, false otherwise.
  • Range Class:

    • Purpose: Implements the NumberGroup interface to represent a contiguous range of integers.
    • Instance Variables: Stores min and max values of the range.
    • Constructor: Range(int min, int max) initializes the range. Assumes min <= max.
    • contains(int num) Method: Returns true if min <= num <= max, false otherwise.
    • Example: new Range(-3, 2) represents the group {-3, -2, -1, 0, 1, 2}.
  • MultipleGroups Class:

    • Purpose: Represents a collection of NumberGroup objects and itself acts as a NumberGroup.
    • Instance Variable: groupList: A List<NumberGroup> storing the individual number groups.
    • Constructor: Initializes groupList.
    • contains(int num) Method:
      • Purpose: Determines if num is contained in any of the NumberGroup objects within groupList.
      • Logic: Iterates through groupList. If any NumberGroup's contains(num) method returns true, the MultipleGroups.contains(num) method returns true. If the loop finishes without finding num in any group, it returns false.
      • Example: If multiple1 contains new Range(5, 8), new Range(10, 12), and new Range(1, 6):
        • multiple1.contains(2) returns true (from new Range(1, 6)).
        • multiple1.contains(9) returns false.
        • multiple1.contains(6) returns true (from both new Range(5, 8) and new Range(1, 6)).



AP Computer Science A 2025 Free-Response Questions Summary

This document outlines the structure and content of the AP Computer Science A Free-Response Questions for the 2025 exam. Section II consists of four free-response questions and has a time limit of 1 hour and 30 minutes. All programming solutions must be written in Java. Partial credit is awarded for incomplete solutions. Students have access to Java Quick Reference information throughout the exam.


Question 1: Dog Walking Company and Dog Walker

This question focuses on simulating a dog-walking business.

1.1 DogWalkCompany Class

  • numAvailableDogs(int hour): Returns the number of dogs available for walking at a specific hour (0-23). The number of available dogs is always greater than 0.
  • updateDogs(int hour, int numberDogsWalked): Decreases the number of available dogs for a given hour by the numberDogsWalked.
    • Preconditions: 0 <= hour <= 23, numberDogsWalked > 0.

1.2 DogWalker Class

  • Instance Variables:
    • maxDogs: The maximum number of dogs a walker can handle simultaneously per hour.
    • company: An instance of DogWalkCompany to which the walker is associated.
  • Constructor DogWalker(int max, DogWalkCompany comp): Initializes maxDogs and company.
    • Precondition: max > 0.
  • walkDogs(int hour) (Part A):
    • Purpose: To walk dogs during a specific hour and return the number of dogs walked.
    • Logic:
      • Determines the number of dogs to walk based on company.numAvailableDogs(hour) and maxDogs. The walker walks the minimum of these two values.
      • Updates the company's available dogs using company.updateDogs(hour, dogsWalked).
      • Returns the actual number of dogs walked.
    • Example: If 10 dogs are available and maxDogs is 4, the walker walks 4 dogs. If 3 dogs are available and maxDogs is 4, the walker walks 3 dogs.
  • dogWalkShift(int startHour, int endHour) (Part B):
    • Purpose: To calculate the total earnings for a dog-walking shift covering a range of hours.
    • Logic: Iterates through each hour from startHour to endHour (inclusive). For each hour:
      • Calls walkDogs(hour) to determine the number of dogs walked.
      • Calculates pay: $5 per dog walked.
      • Adds a $3 bonus if:
        • maxDogs dogs were walked.
        • OR the walk occurs during peak hours (9 to 17, inclusive).
      • Accumulates the earnings for the entire shift.
    • Preconditions: 0 <= startHour <= endHour <= 23.

Question 2: SignedText Class

This question involves creating a SignedText class to manage and manipulate strings with a signature.

2.1 Class Structure

  • Instance Variables: Stores the first name and last name.
  • Constructor SignedText(String firstName, String lastName): Initializes the object with a first and last name.
    • Precondition: lastName.length() >= 1.
  • getSignature(): Returns a formatted signature string.
    • If firstName is empty, returns lastName.
    • If firstName is not empty, returns firstName.charAt(0) + "-" + lastName.
  • addSignature(String text): Modifies a given text string based on the object's signature.
    • Logic:
      • If the signature is not in text, appends the signature to the end of text.
      • If the signature is at the end of text, returns text unchanged.
      • If the signature is at the beginning of text, removes the signature from the beginning and appends it to the end of text.
    • Returns the potentially modified string.

Question 3: Tournament Competitors and Rounds

This question deals with managing competitors and building matches for a tournament.

3.1 Competitor Class

  • Instance Variables: name (String), rank (int).
  • Constructor Competitor(String n, int initialRank): Initializes a competitor with a name and rank.
    • Precondition: initialRank >= 1.

3.2 Match Class

  • Constructor Match(Competitor one, Competitor two): Represents a match between two competitors.

3.3 Round Class

  • Instance Variable: competitorList (ArrayList<Competitor>).
  • Constructor Round(String[ ] names) (Part A):
    • Purpose: Initializes competitorList with Competitor objects.
    • Logic: Creates a Competitor object for each name in the names array. The rank of each competitor is determined by their position in the names array (index 0 is rank 1, index 1 is rank 2, etc.).
    • Example: {"Alex", "Ben", "Cara"} results in competitorList containing Competitor("Alex", 1), Competitor("Ben", 2), Competitor("Cara", 3).
  • buildMatches() (Part B):
    • Purpose: Creates and returns an ArrayList<Match> for the next round of the tournament.
    • Logic: Pairs competitors from competitorList based on rank.
      • Even number of competitors: Pairs the best with the worst, second-best with second-worst, and so on.
      • Odd number of competitors: The highest-ranked competitor is ignored. The remaining competitors are paired as in the even case.
    • Preconditions: competitorList has at least one element and is sorted by rank (best to worst).
    • Postcondition: competitorList remains unchanged.
    • Example (Odd): If competitorList is [{"Ben", 2}, {"Cara", 3}] (after ignoring rank 1), buildMatches returns [Match({"Ben", 2}, {"Cara", 3})].
    • Example (Even): If competitorList is [{"Rei", 1}, {"Sam", 2}, {"Vi", 3}, {"Tim", 4}], buildMatches returns [Match({"Rei", 1}, {"Tim", 4}), Match({"Sam", 2}, {"Vi", 3})].

Question 4: SumOrSameGame Puzzle

This question involves a puzzle represented by a 2D array where elements are cleared by forming pairs.

4.1 SumOrSameGame Class

  • Instance Variable: puzzle (a 2D integer array int[][]).
  • Constructor SumOrSameGame(int numRows, int numCols) (Part A):
    • Purpose: Initializes the puzzle 2D array.
    • Logic: Creates a puzzle array with dimensions numRows x numCols. Each element is filled with a random integer between 1 and 9 (inclusive), with equal probability.
    • Precondition: numRows > 0, numCols > 0.
  • clearPair(int row, int col) (Part B):
    • Purpose: Attempts to find and clear a pair for the element at (row, col).
    • Logic:
      • Searches for another element puzzle[r][c] such that r >= row.
      • The pair is valid if puzzle[row][col] == puzzle[r][c] OR puzzle[row][col] + puzzle[r][c] == 10.
      • If a valid pair is found:
        • Both puzzle[row][col] and puzzle[r][c] are set to 0.
        • Returns true.
      • If multiple pairs exist, any one can be cleared.
      • If no valid pair is found, the puzzle remains unchanged, and the method returns false.
    • Preconditions: row and col are valid indices, and puzzle[row][col] is between 1 and 9.
    • Example: If puzzle[0][1] is 7, it can be paired with puzzle[1][0] (also 7) or puzzle[1][5] (value 3). If paired, both elements become 0. If puzzle[2][0] is 1, and no other element in row 2 or later sums to 9 or is also 1, clearPair returns false.

Exam Information:

  • Section II consists of 4 free-response questions.
  • Time limit: 1 hour and 30 minutes.
  • All code must be in Java.
  • Partial credit is available.
  • Java Quick Reference is accessible.
  • Assume methods are called with valid parameters unless otherwise specified.
  • Use of provided accessible methods is expected; reimplementing them significantly will not receive full credit.
  • Scratch work on paper is allowed, but only responses entered in the application will be graded.
  • Students can navigate between questions in this section.
  • A 5-minute warning will be indicated by the clock turning red.
这里有8套ap真题,我今年要考了,很焦虑,帮我统计一下高频知识点,对应核心terms,中英输出,table展现

苡甜甜甜,你好!以下是根据8套AP计算机科学A历年真题总览,总结出的高频知识点及核心术语(中英文对照),用表格呈现,方便你有针对性地复习。祝你考试顺利,焦虑减半哦!


| 高频知识点 | 英文原词汇/术语 | 中文解释 | 题型领域举例 | |:--------------- |:------------------------ |:------------ |:------------------------ | | 数组与ArrayList | Array, ArrayList | 数组与列表 | 遍历、查找、排序、复制、反转等 [27][79][128] | | 字符串处理 | String, substring, indexOf, equals | 字符串操作 | 查找子串、替换、拼接、字符判断 [72][130][22] | | 类与对象 | Class, Object, Constructor, Instance Variable | 面向对象基本概念 | 构造方法、对象属性、封装、实例化 [9][129] | | 继承与多态 | Inheritance, extends, implements, Polymorphism, Interface | 继承、多态、接口 | 子类构造、方法重写、接口实现 [14][21][40] | | 封装及访问控制 | private, public, getter/setter | 封装、访问修饰 | 成员变量私有,getter/setter方法 [131][150] | | 控制结构 | if-else, for, while, do-while, switch | 条件与循环结构 | 条件分支、循环遍历、嵌套循环 [16][33][60] | | 静态成员 | static, static method/variable | 静态方法/静态变量 | 比较static与实例成员 [53] | | 集合类 | List, Set, Map, ArrayList | 集合类操作 | 元素添加、删除、遍历、查找 [5][48] | | 方法签名与重载 | Method signature, Overloading | 方法重载 | 同名不同参的方法 [2][131] | | 接口与抽象类 | Interface, implements, abstract | 接口、抽象类 | 接口声明与实现,抽象方法 [21][151] | | 递归 | Recursion | 递归算法 | 递归函数、递归终止条件 [12][26][38] | | 排序与算法 | Sorting, selection sort, bubble sort | 排序算法 | 选择排序、嵌套循环 [27][28] | | 搜索/查找 | Search, linear search, binary search | 查找算法 | 顺序查找、二分查找等 [97][126] | | 二维数组 | 2D Array | 二维数组 | 行优先/列优先遍历 [4][103] | | 数学与逻辑表达式| Modulo, integer division, &&, ||, ! | 数学和逻辑表达式 | 取余、整除、关系运算 [21][20] | | 异常与边界 | Exception, bounds checking | 异常处理与越界 | 下标越界、空指针 [32][52] | | 深浅拷贝 | Deep Copy, Shallow Copy | 深拷贝/浅拷贝 | 对象引用与new的区别 [27] | | API文档与规范 | Java Quick Reference, Documentation | Java 快速参考 | 按规范调用标准库方法 [11][34] |


常见核心terms短语补充(按领域)

  • 集合类: add, remove, get, size, clear
  • 字符串: length, charAt, substring, replace, equals
  • 数组/列表遍历: for-each loop, index-based loop
  • OOP: field, method, constructor, inheritance, overriding, polymorphism, interface, abstract
  • 异常处理: try-catch, NullPointerException, IndexOutOfBoundsException
  • 算法: merge, swap, compare, sort, search, inversion

温馨建议:

  • 高频考点最常出现在填空、完型、简答题、完整程序编写等类型。
  • 真题里对象设计题、接口实现题、数组/字符串处理题、嵌套循环和递归题一定要熟练。
  • 这些术语都要能看懂题干、理解选择题选项,写程序时兼顾命名和风格。

有什么概念/考试内容不熟悉,都可以让我帮你加强记忆、举例或练习!也可以帮你生成知识点专属记忆卡!

集合知识点我没学好,可以给我具体讲讲,配上真题教教我

苡甜甜甜,你好!你提到集合没学好,下面我会用AP真题中的经典考点+详细讲解+例题解析的方式,帮你把集合List/Set/Map以及常考操作讲透。你可以直接用表格预览、再看例题细节和总结。


一、AP考试中常见集合类型与操作【中英对照】

| 英文名 | 中文名 | 常考操作 | 示例构造/说明 | |:--------------|:------------|:----------------------------|:-----------------------------| | List/ArrayList| 列表/动态数组| add、remove、get、set、size | ArrayList<String> list = new ArrayList<>(); | | Set/HashSet | 集合(无重复)| add、remove、contains、size | Set<Integer> set = new HashSet<>(); | | Map/HashMap | 映射/字典 | put、get、containsKey、remove| Map<String, Integer> map = new HashMap<>(); |


【1】List/ArrayList(有序/可重复)讲解

  • 基本用法:存一组有序元素,元素可以重复。常用下标访问。
  • 核心操作
    • add(element) : 增加元素
    • remove(index)remove(object) : 删除元素
    • get(index) : 取某个位置
    • set(index, value) : 修改某个位置
    • size() : 长度

【真题例子】

  • 2013年FRQ题型:
public void updateDownloads(List<String> titles) {
    for (String title : titles) {
        DownloadInfo found = getDownloadInfo(title);
        if (found == null) {
            downloadList.add(new DownloadInfo(title));
        } else {
            found.incrementTimesDownloaded();
        }
    }
}

【考点】


【2】Set/HashSet(无序/无重复)讲解

  • 概念:集合不能有重复元素,不能按下标访问,只能按元素找。
  • 常用操作
    • add(element) : 添加且自动去重
    • contains(element) : 查是否在集合中
    • remove(element) : 移除指定元素
    • size() : 集合元素数量

【真题情景分析】

  • AP题有时考查如何判断某个值在不在某组、无重复自动去重。

【3】Map/HashMap(键-值对)讲解

  • 概念:key-value映射,key唯一,value可重复,可以根据key高效查找。
  • 常用操作
    • put(key, value) : 新增/修改键-值对
    • get(key) : 根据key查找
    • remove(key) : 根据key移除
    • containsKey(key) : 判断某个key在不在

【真题例子】

  • 如果需要统计某元素出现次数(如字符串统计或投票问题),常用Map。

二、典型真题例子讲解

1. 查找与插入(List)

【例题】(简化)

ArrayList<Integer> nums = new ArrayList<>();
nums.add(1); nums.add(2); nums.add(3);
// 查找并增加
if (!nums.contains(5)) {
   nums.add(5); // 只加不重复的
}

【考点】

  • 遍历、判重插入(虽List可以重复,这里用contains避免)。

2. 元素统计(Map)

【例题】

Map<String, Integer> voteCount = new HashMap<>();
for (String vote : votes) {
    voteCount.put(vote, voteCount.getOrDefault(vote, 0) + 1);
}

【考点】

  • Map自动创建和计数,key作为唯一标识,适合投票/词频等题。

3. 去重判定(Set)

【例题】

Set<Integer> set = new HashSet<>();
for (int num : nums) {
    set.add(num);
}
boolean hasDuplicate = set.size() != nums.length;

【考点】

  • 利用Set自动去重,size变化判断重复。

三、真题技巧与易错点

  1. 遍历List删除元素:用Iterator或倒序,否则容易漏删/越界。
  2. 避免NullPointerException:Map用containsKey判断再get。
  3. 区分List/Set/Map特性:List能存重复元素,Set不能,Map按键查找。

四、真题秒杀小练

1. 判断一个int数组是否有重复元素?

Set<Integer> set = new HashSet<>();
for(int num : nums){
    if(!set.add(num)){
        return true; // 有重复
    }
}
return false;

2. 将String数组所有单词统计出现次数?

Map<String, Integer> map = new HashMap<>();
for(String s : arr){
    map.put(s, map.getOrDefault(s, 0) + 1);
}

五、你还需要重点掌握的常见术语(关键字对照)

| 英文 | 中文 | 含义 | |---|---|---| | add | 添加 | 向集合增加元素 | | get | 获取 | 按下标/Key取元素 | | remove | 移除 | 删除元素 | | contains | 包含 | 集合中是否有某元素 | | put | 新增映射 | Map中放入键-值对 | | size | 长度 | 集合元素数量 |


★有具体某道题不会、某份试卷卡住,直接发出来,我帮你一步一步讲解代码思路和集合操作怎么用!

随时加深理解、可以反复问我哦!相信你能掌握集合击穿AP!

Ask Sia for quick explanations, examples, and study support.

Let's Get in Touch

AskSia on InstagramAskSia on TikTokAskSia on DiscordAskSia on FacebookAskSia on LinkedInAskSia on Reddit