Verityprep
Question Bank · Unit 2

AP® Computer Science A Selection and Iteration FRQ

Work through AP Computer Science A free-response questions on Selection and Iteration, 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: Iteration Clear filter

Questions 1–7 of 7
  1. 1
  2. 2
  3. 3
  4. 4
  5. 5
  6. 6
  7. 7

Question 1

Free response Iteration
This question involves dog walkers who are paid through a dog-walking company to take dogs for one-hour walks. A dog-walking company has a varying number of…

Sign up now. It's free!

See the full question with its answer and worked solution.

Question 2

Free response Iteration
A teacher wants to analyze student-submitted text. You will write methods for a TextAnalyzer class. The class has a single instance variable: private String…

Sign up now. It's free!

See the full question with its answer and worked solution.

Question 3

Free response Iteration
The FestivalManager class contains methods used for a game booth at a school festival. public class FestivalManager { / * * Returns a random integer from 1…

Sign up now. It's free!

See the full question with its answer and worked solution.

Question 4

Free response Iteration

A small neighborhood grocery store tracks how many customers are waiting in each of its checkout lanes. The store uses the class GroceryStore, whose skeleton is shown below.

public class GroceryStore
{
    /** The number of customers currently waiting in each lane.
     *  laneQueues[k] stores the customers in lane k (0-based).
     *  The array is never null and has at least one element. */
    private int[] laneQueues;

    /** The number of seconds it takes to serve one customer
     *  in any lane. Always positive. */
    private int secondsPerCustomer;

    /** Constructs a GroceryStore with the given queue snapshot and
     *  per-customer service time. */
    public GroceryStore(int[] queues, int secs)
    {
        /* not shown */;
    }

    /** Returns the estimated wait time, in seconds, for a customer
     *  who joins the back of lane laneIndex right now. Part (a) */
    public int estimatedWait(int laneIndex)
    {
        /* part (a) */;
    }

    /** Returns the index of the lane with the shortest estimated wait.
     *  If multiple lanes are tied, the lowest such index is returned.
     *  Part (b) */
    public int fastestLane()
    {
        /* part (b) */;
    }

    // Other methods and constructors are not shown.
}

Part A

Write the method estimatedWait. A customer joining the back of a lane must wait for every customer already in that lane to be served plus the time to be served themselves. Each customer takes exactly secondsPerCustomer seconds.

For example, suppose secondsPerCustomer is 45 and laneQueues is {3, 1, 4, 2}. The following table shows the expected return values.

Call Returned Value Explanation
estimatedWait(0) 180 3 ahead + 1 self = 4 × 45
estimatedWait(1) 90 1 ahead + 1 self = 2 × 45
estimatedWait(2) 225 4 ahead + 1 self = 5 × 45
estimatedWait(3) 135 2 ahead + 1 self = 3 × 45

Assume laneIndex is a valid index in laneQueues.

Part B

Write the method fastestLane. It returns the index of the lane with the shortest estimated wait for a new customer joining now. If two or more lanes are tied for the minimum, return the smallest such index.

For example, if secondsPerCustomer is 30 and laneQueues is {2, 0, 2, 0, 3}, then the estimated waits are {90, 30, 90, 30, 120}. The minimum is 30, achieved by lanes 1 and 3, so fastestLane() returns 1.

You must call estimatedWait appropriately to receive full credit. Assume estimatedWait works as specified regardless of what you wrote in Part A.

The answer and the full solution open in a window.

Question 5

Free response Iteration

An electric utility models its service area as a network of power plants and demand regions. The utility keeps three parallel data structures:

  • generation — a double[] where generation[p] is the rated output of plant p, in megawatts (MW).
  • demand — a double[] where demand[r] is the instantaneous load of region r, in megawatts (MW).
  • distance — a double[][] where distance[p][r] is the length of the transmission line from plant p to region r, in kilometers. A value of -1.0 indicates that no line exists.

Power delivered to a region is reduced by transmission loss. The utility uses the following efficiency factor for a line of length d kilometers:

efficiency(d) = 1.0 - 0.002 * d / / d >= 0

If the efficiency is negative for some d, the method is still required to return the literal result of the formula (the utility will reject such a route elsewhere).

You will implement two methods of the EnergyGrid class. A partial class declaration is shown below.

public class EnergyGrid
{
    private double[] generation;
    private double[] demand;
    private double[][] distance;
    / / constructor and other methods not shown
    public double powerDelivered(int plant, int region)
    { / * to implement in part (a) * / }
    public int closestAdequatePlant(int region)
    { / * to implement in part (b) * / }
}

Part (a) — powerDelivered

Write the method powerDelivered. The method returns the power (in MW) that plant plant delivers to region region, computed as generation[plant] * efficiency(distance[plant][region]). If no line exists between the plant and the region (distance[plant][region] equals -1.0), the method must return 0.0 without computing the formula.

Method Signature

public double powerDelivered(int plant, int region)

For example, suppose generation = {400.0, 260.0}, demand = {150.0, 300.0, 90.0}, and

distance = {
    { 50.0, 120.0, - 1.0 },
    {220.0, 80.0, 30.0 }
}

Then powerDelivered(0, 0) returns 400.0 * (1.0 - 0.002 * 50.0) = 360.0. powerDelivered(0, 2) returns 0.0 because no line exists. powerDelivered(1, 1) returns 260.0 * (1.0 - 0.002 * 80.0) = 218.4.

Part (b) — closestAdequatePlant

Write the method closestAdequatePlant. The method returns the index of the plant that is closest to region region (smallest distance[plant][region]) among all plants that satisfy both of the following conditions:

  • a transmission line exists between the plant and the region; that is, distance[plant][region] is not -1.0;
  • the power delivered to the region by that plant, as computed in part (a), is at least demand[region].

If no plant satisfies both conditions, the method returns -1. If several plants tie for the smallest distance, the method returns the smallest index among them.

Assume part (a) is implemented correctly. You must call powerDelivered; do not repeat its formula.

Method Signature

public int closestAdequatePlant(int region)

Continuing the example above: for closestAdequatePlant(1), plant 0 delivers 400 * (1 - 0.002 * 120) = 304.0 MW, which meets the 300 MW demand, and plant 1 delivers 260 * (1 - 0.002 * 80) = 218.4 MW, which does not. Only plant 0 qualifies, so the method returns 0. For closestAdequatePlant(2) only plant 1 has a line (distance 30, delivery 260 * 0.94 = 244.4 MW > 90), so the method returns 1.

The answer and the full solution open in a window.

Question 6

Free response Iteration

A technical workshop offers several sessions throughout the day. The workshop stores information about each session in three parallel arrays.

  • capacity[i] is the maximum number of students allowed in session i.
  • enrolled[i] is the number of students currently enrolled in session i.
  • canceled[i] is true if session i has been canceled and false otherwise.

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

public class WorkshopSchedule
{
    private int[] capacity;
    private int[] enrolled;
    private boolean[] canceled;

    // constructor not shown

    public int openSeats(int session)
    { /* to be written in part (a) */ }

    public int firstAvailableSession(int needed)
    { /* to be written in part (b) */ }
}

Part (a). Write the method openSeats, which returns the number of open seats in session session. If the session is canceled, the method returns 0.

For example, if capacity[2] = 24, enrolled[2] = 19, and canceled[2] = false, then openSeats(2) returns 5. If canceled[2] = true, then openSeats(2) returns 0.

Part (b). Write the method firstAvailableSession, which returns the index of the first session that has at least needed open seats. The method must ignore canceled sessions. If no session has at least needed open seats, the method returns -1.

Assume part (a) works as intended. Your solution to part (b) must call openSeats.

The answer and the full solution open in a window.

Question 7

Free response Iteration

The ClubAttendance class stores the number of students who attended an after-school club on each recorded meeting day. The declaration below shows the instance variable and method headers.

public class ClubAttendance
{
    private int[] attendance;

    public ClubAttendance(int[] data)
    {
        attendance = data;
    }

    public int countBusyDays(int minStudents)
    { /* to be implemented in part (a) */ }

    public int firstLongRun(int minStudents, int runLength)
    { /* to be implemented in part (b) */ }
}

Part (a). Write the method countBusyDays, which returns the number of entries in attendance that are greater than or equal to minStudents.

For example, if attendance contains {12, 18, 16, 9, 18, 20}, then countBusyDays(18) returns 3.

Part (b). Write the method firstLongRun, which returns the starting index of the first sequence of runLength consecutive entries in attendance that are each greater than or equal to minStudents. If no such sequence exists, the method returns -1.

For example, if attendance contains {12, 18, 16, 19, 20, 10}, then firstLongRun(16, 3) returns 1 because the first run of three qualifying values begins at index 1. The run {18, 16, 19} qualifies, and no earlier run does.

The answer and the full solution open in a window.
Question 1 of 7