Verityprep
Question Bank · Unit 4

AP® Computer Science A Data Collections FRQ

Work through AP Computer Science A free-response questions on Data Collections, then check each answer against a worked solution.

Free · no sign-up Open questions need no account. Sign up or log in to open the rest.

Subtopic: Arraylists Clear filter

Questions 41–50 of 52
  1. 41
  2. 42
  3. 43
  4. 44
  5. 45
  6. 46
  7. 47
  8. 48
  9. 49
  10. 50

Question 41

Free response Arraylists

A neighborhood book club meets monthly to discuss and rate books. Members rate each book on a scale of 1 to 10, and the club maintains two parallel ArrayLists: one for book titles and one for their average ratings. The BookClub class provides methods to help members select their next read.

PART A

Write the method public ArrayList<String> getTopRated(ArrayList<String> titles, ArrayList<Integer> ratings, int threshold) that returns a new ArrayList containing only the titles whose corresponding rating is greater than or equal to threshold, preserving the original order.

For example, if titles is ["Dune", "1984", "Cosmos", "Beloved"] and ratings is [9, 7, 8, 6] with threshold 8, the method returns ["Dune", "Cosmos"].

public ArrayList<String> getTopRated(ArrayList<String> titles, ArrayList<Integer>
    ratings, int threshold) {

PART B

Write the method public String recommend(ArrayList<String> titles, ArrayList<Integer> ratings) that removes and returns the title with the highest rating. If there is a tie, remove and return the one appearing earliest in the list. Both the titles and ratings lists should have the corresponding element removed.

For example, if titles is ["Dune", "1984", "Cosmos"] and ratings is [9, 7, 9], the method returns "Dune" (first with highest rating 9) and both lists are reduced to ["1984", "Cosmos"] and [7, 9].

public String recommend(ArrayList<String> titles, ArrayList<Integer> ratings) {
The answer and the full solution open in a window.

Question 42

Free response Arraylists
This question involves the design of a class that maintains a collection of books on a library shelf. The following Book class is provided. public class Book {…

Sign up now. It's free!

See the full question with its answer and worked solution.

Question 43

Free response Arraylists
A LibraryCart stores books that a student plans to check out. public class Book { / * * Returns the title of this book. * / public String getTitle() { / *…

Sign up now. It's free!

See the full question with its answer and worked solution.

Question 44

Free response Arraylists

SurveyResults analyzes survey scores. scores is a nonnull ArrayList, possibly empty, with every value in [0,100]. The constructor keeps the supplied list reference.

public class SurveyResults {
 private java.util.ArrayList scores
 public SurveyResults(java.util.ArrayList initial){scores=initial;}
 // Implement countAbove and trim.
}
OperationResult
Initial scores[85,42,90,42,73,100,15]
countAbove(50)4
trim(40,90)[85,42,90,42,73]
then trim(50,80)[73]

(a) Implement countAbove(int threshold), returning the number of scores strictly greater than threshold.

(b) Implement trim(int minAccept,int maxAccept), removing scores outside the inclusive range [minAccept,maxAccept], while preserving the relative order of all remaining values. Assume 0 <= minAccept <= maxAccept <= 100. Handle empty lists, removal of every element, and consecutive removals.

The answer and the full solution open in a window.

Question 45

Free response Arraylists

A linguist is studying word usage in a corpus. Given an ArrayList<String> of the words that appear in a document (in order, with possible repetitions), the linguist wants the list of most common words in that document.

Write a static method mostFrequent that, given such a list, returns a new ArrayList<String> containing every word whose number of occurrences in words equals the maximum number of occurrences attained by any word. In the returned list:

  • each qualifying word appears exactly once, even if it occurs many times in words;
  • the qualifying words appear in the order of their first occurrence in words.

Two words are considered the same only if they are equal as strings (case-sensitive). The parameter words must not be modified. If words is empty, return an empty list.

Method Signature

public static ArrayList<String> mostFrequent(ArrayList<String> words)

Examples

Input words Returned list Explanation
["to","be","or","not","to","be"] ["to","be"] Both appear twice; "to" occurs first, then "be".
["red","blue","red","green","blue","red"] ["red"] Max count is 3 ("red"); "blue" has count 2.
["a","b","c","d"] ["a","b","c","d"] All words tie at count 1; order is preserved.
["Cat","cat","Cat"] ["Cat"] Case-sensitive: "Cat" has count 2, "cat" has count 1.
[] [] Empty input → empty output.
The answer and the full solution open in a window.

Question 46

Free response Arraylists
This question involves a movie streaming service that stores a list of movies and selects pairings for "double feature" slots — two movies that together fit…

Sign up now. It's free!

See the full question with its answer and worked solution.

Question 47

Free response Arraylists

A retail system models each item for sale as a Product and uses a Store object to hold every product currently tracked by the store. The two classes are shown below; only the method totalValueOfLowStock in Store is left for you to complete. Everything else is already written.

public class Product
{
    private String name;
    private double price;
    private int quantity;

    public Product(String theName, double thePrice, int theQuantity)
    {
        name = theName;
        price = thePrice;
        quantity = theQuantity;
    }

    public String getName()      { return name; }
    public double getPrice()     { return price; }
    public int getQuantity()   { return quantity; }
}

public class Store
{
    /** Inventory of products currently tracked by this store. Never null. */
    private ArrayList<Product> inventory;

    public Store(ArrayList<Product> startingInventory)
    {
        inventory = startingInventory;
    }

    /** Returns the total dollar value of all products in inventory whose current
     *  quantity is strictly less than threshold. The dollar value of a single
     *  product is its price multiplied by its quantity. If no product has a
     *  quantity below threshold, the method returns 0.0.
     *  @param threshold the cutoff quantity; assumed to be non-negative
     *  @return the sum of price * quantity over all low-stock products
     */
    public double totalValueOfLowStock(int threshold) { /* to implement */ }
}

Write the method totalValueOfLowStock. The method must iterate over every product in inventory and accumulate the dollar value price * quantity for each product whose current quantity is strictly less than threshold.

Example

Suppose inventory holds three products:

{name:"widget", price:4.50, quantity:2}, {name:"gizmo", price:10.00, quantity:7}, {name:"bolt", price:0.25, quantity:3}.

A call to totalValueOfLowStock(5) selects the "widget" (quantity 2) and the "bolt" (quantity 3) because 7 is not less than 5. The returned value is \(4.50 \times 2 + 0.25 \times 3 = 9.75\).

public double totalValueOfLowStock(int threshold)
The answer and the full solution open in a window.

Question 48

Free response Arraylists

A cinema management system models each scheduled showing as a Movie object and keeps every showing currently on the schedule inside a Theater object. The two classes are shown below; only the method averageRatingAtLeast in Theater is left for you to complete. Everything else is already written.

public class Movie
{
    private String title;
    private int lengthMinutes;
    private double rating;

    public Movie(String theTitle, int theLength, double theRating)
    {
        title = theTitle;
        lengthMinutes = theLength;
        rating = theRating;
    }

    public String getTitle()        { return title; }
    public int getLengthMinutes()   { return lengthMinutes; }
    public double getRating()      { return rating; }
}

public class Theater
{
    /** All movies currently scheduled at this theater. Never null. */
    private ArrayList<Movie> showings;

    public Theater(ArrayList<Movie> startingShowings)
    {
        showings = startingShowings;
    }

    /** Returns the average rating of every movie in showings whose length is at least
     *  minLength minutes. If no movie meets the length requirement, returns 0.0.
     *  @param minLength the inclusive lower bound on length, in minutes; assumed non-negative
     *  @return the mean rating of qualifying movies, or 0.0 when no movie qualifies
     */
    public double averageRatingAtLeast(int minLength) { /* to implement */ }
}

Write the method averageRatingAtLeast. The method must iterate over every Movie in showings, accumulate the rating of each movie whose length in minutes is at least minLength, and return the mean of those ratings as a double. If no movie meets the length requirement, the method returns 0.0.

Example

Suppose showings holds four movies:

{title:"Alpha", lengthMinutes:90, rating:4.0}, {title:"Bravo", lengthMinutes:135, rating:4.5}, {title:"Charlie", lengthMinutes:75, rating:3.0}, {title:"Delta", lengthMinutes:120, rating:3.5}.

A call to averageRatingAtLeast(120) selects the movies whose length is at least 120 minutes — Bravo and Delta — and returns the mean of their ratings: (4.5 + 3.5) / 2 = 4.0.

A call to averageRatingAtLeast(200) finds no qualifying movie and therefore returns 0.0.

public double averageRatingAtLeast(int minLength)
The answer and the full solution open in a window.

Question 49

Free response Arraylists

Information about applicants for a scholarship program is stored in Applicant objects.

public class Applicant
{
    private String name;
    private int score;
    private boolean complete;

    public Applicant(String n, int s, boolean c)
    {
        name = n;
        score = s;
        complete = c;
    }

    public String getName()
    {
        return name;
    }

    public int getScore()
    {
        return score;
    }

    public boolean isComplete()
    {
        return complete;
    }
}

The ScholarshipGroup class stores a list of applicants.

public class ScholarshipGroup
{
    private ArrayList<Applicant> applicants;

    public ScholarshipGroup(ArrayList<Applicant> list)
    {
        applicants = list;
    }

    public ArrayList<String> finalists(int minScore)
    { /* to be written */ }
}

Write the method finalists, which returns a new ArrayList<String> containing the names of all applicants who satisfy both of the following conditions.

  • The applicant's form is complete.
  • The applicant's score is at least minScore.

Among the applicants who satisfy those conditions, only applicants whose score is equal to the highest qualifying score should appear in the returned list. Names in the returned list must appear in the same order as the corresponding applicants appear in applicants. If no applicant qualifies, the method returns an empty list.

For example, if the qualifying applicants have scores 81, 94, 94, 88, the returned list should contain the names of the two applicants whose score is 94, in their original order.

The answer and the full solution open in a window.

Question 50

Free response Arraylists
Information about players in a school league is stored in Player objects. public class Player { private String name; private int points; private boolean active;…

Sign up now. It's free!

See the full question with its answer and worked solution.

Question 41 of 52
Page 5 of 6