Verityprep
Question Bank · Unit 4

AP® Computer Science A Data Collections Practice Questions

Work through AP Computer Science A practice 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.

Questions 1,151–1,160 of 1,222
  1. 1151
  2. 1152
  3. 1153
  4. 1154
  5. 1155
  6. 1156
  7. 1157
  8. 1158
  9. 1159
  10. 1160

Question 1151

Free response Arrays
A hardware store tracks how many units of a particular item are in stock at the end of each day. The class StockLog stores these daily counts in the array…

Sign up now. It's free!

See the full question with its answer and worked solution.

Question 1152

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 1153

Free response 2D Arrays

A topographic survey is stored in a class HeightMap, which uses a two-dimensional array to hold the elevation of each grid cell. Row 0 is the northernmost row and column 0 is the westernmost column. All rows have the same length. The grid is at least \(1 \times 1\).

public class HeightMap
{
    /** Elevation grid; heights[r][c] is the elevation of the cell at row r, column c.
     *  Guaranteed to be a rectangular, non-empty 2D array of integers. */
    private int[][] heights;

    public HeightMap(int[][] grid)
    {
        heights = grid;
    }

    /** Part: see below. */
    public boolean[][] peaks() { /* to implement */ }
}

Write the method peaks. The method returns a newly constructed boolean array of the same dimensions as heights. Entry [r][c] in the returned array is true if and only if the elevation at cell (r, c) is strictly greater than the elevation of every one of its orthogonal neighbors that exists in the grid. The orthogonal neighbors of (r, c) are the cells directly north, south, west, and east: (r-1, c), (r+1, c), (r, c-1), and (r, c+1). Neighbors outside the grid are simply ignored when making the comparison.

A corner cell has only two neighbors; an edge cell has only three neighbors; an interior cell has four. A cell with any neighbor at or above its own elevation is not a peak. A cell in a \(1 \times 1\) grid has no neighbors and is therefore a peak.

Example

Let heights be the grid

{ {1, 4, 2}, {3, 2, 5}, {1, 1, 2} }.

The call peaks() returns

{ {false, true, false}, {true, false, true}, {false, false, false} }.

Explanation: (0,1) = 4 beats its existing neighbors 1, 2, 2; (1,0) = 3 beats 1, 2, 1; (1,2) = 5 beats 2, 2, 2. Every other cell has at least one neighbor at least as tall as itself.

public boolean[][] peaks()

Open each "Show solution" accordion above to compare your response against the reference implementation and scoring notes.

const TOTAL = 42; const TOTAL_SECONDS = 3 * 60 * 60; let remaining = TOTAL_SECONDS; let timerId = null; let started = false; let submitted = false; function fmt(s) { let h = Math.floor(s / 3600); let m = Math.floor((s % 3600) / 60); let x = s % 60; function p(n) { return n < 10 ? "0" + n : "" + n; } return h + ":" + p(m) + ":" + p(x); } function tick() { if (remaining <= 0) { clearInterval(timerId); document.getElementById("timerEl").textContent = "0:00:00"; document.getElementById("timerEl").classList.add("danger"); return; } remaining--; const el = document.getElementById("timerEl"); el.textContent = fmt(remaining); if (remaining <= 600 && remaining > 300) el.classList.add("warn"); if (remaining <= 300) { el.classList.remove("warn"); el.classList.add("danger"); } } function mulberry32(a) { return function() { a |= 0; a = a + 0x6D2B79F5 | 0; let t = a; t = Math.imul(t ^ t >>> 15, t | 1); t ^= t + Math.imul(t ^ t >>> 7, t | 61); return ((t ^ t >>> 14) >>> 0) / 4294967296; }; } function shuffleQuestions() { const host = document.getElementById("mcqHost"); const qs = Array.from(host.querySelectorAll(".qb")); const rng = mulberry32(2026); for (let i = qs.length - 1; i > 0; i--) { const j = Math.floor(rng() * (i + 1)); if (j !== i) host.insertBefore(qs[i], qs[j]); } const kept = Array.from(host.querySelectorAll(".qb")); kept.forEach((q, idx) => { const n = q.querySelector(".qn"); if (n) n.textContent = "Question " + (idx + 1); }); buildDots(kept.length); } function buildDots(n) { const host = document.getElementById("navDots"); host.innerHTML = ""; for (let i = 0; i < n; i++) { const d = document.createElement("div"); d.className = "ndot"; d.textContent = i + 1; d.onclick = () => { const qs = document.querySelectorAll("#mcqHost .qb"); if (qs[i]) qs[i].scrollIntoView({ behavior: "smooth", block: "start" }); }; host.appendChild(d); } } function updateProgress() { const qs = document.querySelectorAll("#mcqHost .qb"); let answered = 0; const dots = document.querySelectorAll(".ndot"); qs.forEach((q, i) => { const chosen = q.querySelector(".op.sel"); if (chosen) { answered++; if (dots[i]) dots[i].classList.add("done"); } else { if (dots[i]) dots[i].classList.remove("done"); } }); document.getElementById("progFill").style.width = (100 * answered / qs.length) + "%"; document.getElementById("progLbl").textContent = answered + " / " + qs.length + " answered"; } function pick(el) { if (submitted) return; const qb = el.closest(".qb"); qb.querySelectorAll(".op").forEach(o => o.classList.remove("sel")); el.classList.add("sel"); updateProgress(); } function ap(c) { const p = 100 * c / TOTAL; if (p >= 70) return 5; if (p >= 55) return 4; if (p >= 40) return 3; if (p >= 25) return 2; return 1; } function submitMCQ() { if (submitted) return; submitted = true; let correct = 0; document.querySelectorAll("#mcqHost .qb").forEach(qb => { const answer = qb.getAttribute("data-answer"); const opts = qb.querySelectorAll(".op"); let chosen = null; opts.forEach(op => { if (op.classList.contains("sel")) chosen = op.getAttribute("data-q"); }); opts.forEach(op => { const k = op.getAttribute("data-q"); if (k === answer) op.classList.add("correct"); else if (k === chosen) op.classList.add("wrong"); }); const ex = qb.querySelector(".ex"); if (ex) ex.classList.add("show"); if (chosen === answer) correct++; }); document.getElementById("scoreBig").textContent = correct; document.getElementById("rawScore").textContent = correct + " / " + TOTAL; document.getElementById("pctScore").textContent = Math.round(100 * correct / TOTAL) + "%"; document.getElementById("apScore").textContent = ap(correct); document.getElementById("timeLeft").textContent = fmt(remaining); document.getElementById("scorePanel").classList.add("show"); document.getElementById("scorePanel").scrollIntoView({ behavior: "smooth", block: "start" }); } function startExam() { if (started) return; started = true; document.getElementById("coverPage").classList.add("hidden"); document.getElementById("examPage").classList.remove("hidden"); shuffleQuestions(); updateProgress(); timerId = setInterval(tick, 1000); }
The answer and the full solution open in a window.

Question 1154

Multiple choice Arrays
Consider the following code segment, where data is a non-empty int array containing only positive values terminated by a single -1 sentinel that appears…

Sign up now. It's free!

See the full question with its answer and worked solution.

Question 1155

Multiple choice Arrays
Consider the following class. public class Stack3 { private int[] data; private int top; public Stack3() { data = new int[3]; top = 0; } public boolean push(int…

Sign up now. It's free!

See the full question with its answer and worked solution.

Question 1156

Multiple choice 2D Arrays
Consider the following code segment.
int[][] g = { {1, 2, 3, 4},
               {5, 6, 7, 8},
               {9, 10, 11, 12} };
int sum = 0;
for (int r = 0; r < g.length; r++)
{
    for (int c = 0; c < g[0].length; c++)
    {
        if (r == c || c == g[0].length - 1 - r)
        {
            sum = sum + g[r][c];
        }
    }
}
System.out.println(sum);
What is printed when the code segment executes?
Pick an answer, then check it. The solution opens in a window.

Question 1157

Multiple choice Recursion
Consider the following method. public static int mystery(int n) { if (n <= 1) { return n;…

Sign up now. It's free!

See the full question with its answer and worked solution.

Question 1158

Multiple choice Sorting And Searching
Consider an int array a initially equal to {40, 18, 25, 7, 31, 12}. Selection sort, sorting in ascending order, repeatedly finds the…

Sign up now. It's free!

See the full question with its answer and worked solution.

Question 1159

Multiple choice Arrays
Consider an int array a initially equal to {40, 12, 25, 7, 31, 18}. Insertion sort, sorting in ascending order, treats the prefix of length k as already sorted…

Sign up now. It's free!

See the full question with its answer and worked solution.

Question 1160

Multiple choice Using Text Files
A text file contains the following exact contents (one record per line, comma-separated):
name,grade,present
Ali,87,true
Bea,72,false
Cyd,91,true
Dax,54,true
A program creates a properly constructed Scanner sc reading that file, then runs the following code. Assume any imports needed are present.
sc.nextLine();
int total = 0;
int n = 0;
while (sc.hasNext())
{
    String line = sc.nextLine();
    String[] parts = line.split(",");
    if (parts[2].equals("true"))
    {
        total = total + Integer.parseInt(parts[1]);
        n = n + 1;
    }
}
sc.close();
double avg = total * 1.0 / n;
What is the value of avg when the segment finishes?
Pick an answer, then check it. The solution opens in a window.
Question 1,151 of 1,222
Page 116 of 123