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: 2D Arrays Clear filter

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

Question 41

Free response 2D Arrays
A TerrainMap object stores elevation values in a rectangular 2D array. public class TerrainMap { private int[][] heights; / * * To be written. * / public int…

Sign up now. It's free!

See the full question with its answer and worked solution.

Question 42

Free response 2D Arrays

A grayscale image is represented as a rectangular 2D array of pixel values, where each entry is an integer in [0, 255]. The class ImageFilter provides operations on such images.

public class ImageFilter
{
    /** The pixel grid. pixels[r][c] is the pixel at row r, column c.
    * Each value is in [0, 255]. The grid has at least one row and
    * one column, and every row has the same length. */
    private int[][] pixels;
    /** Constructs an ImageFilter around the given grid. */
    public ImageFilter(int[][] p)
    {
        pixels = p;
    }
    /** Returns the maximum pixel value in the row range
    * [startRow, endRow] (inclusive on both ends). Part (a) */
    public int brightestIn(int startRow, int endRow)
    {
        /* part (a) */;
    }
    /** Applies an "invert then clip" filter to every pixel of pixels,
    * modifying pixels in place. Part (b) */
    public void invertAndClip(int floor)
    {
        /* part (b) */;
    }
    // Other methods are not shown.
}

Part A

Write the method brightestIn. It returns the largest pixel value found anywhere in rows startRow through endRow of pixels, inclusive on both ends.

For example, suppose pixels is the following \(4 \times 5\) grid.

{ { 40, 12, 7, 30, 50 },
{ 15, 80, 20, 10, 5 },
{ 33, 33, 33, 33, 33 },
{ 99, 0, 60, 5, 42 } }

Then brightestIn(0, 1) returns 80, brightestIn(2, 2) returns 33, and brightestIn(0, 3) returns 99.

Assume 0 <= startRow <= endRow < pixels.length.


Part B

Write the method invertAndClip. It modifies pixels in place by applying the following to every pixel p:

  1. Compute the inverted value 255 − p.
  2. If that inverted value is strictly less than floor, replace the pixel with floor (clip upward).
  3. Otherwise, store the inverted value.

For example, if floor is 50 and a pixel has value 210, then \(255 - 210 = 45\), which is below 50, so the pixel becomes 50. If a pixel has value 100, then \(255 - 100 = 155\), which is not below 50, so the pixel becomes 155.

Using the \(4 \times 5\) example from Part A and calling invertAndClip(50), the resulting grid is:

{ { 215, 243, 248, 225, 205 },
{ 240, 175, 235, 245, 250 },
{ 222, 222, 222, 222, 222 },
{ 156, 255, 195, 250, 213 } }

(Every inverted value was already at least 50.) If instead the row { 240, 250, 252, 200, 220 } were present, calling invertAndClip(50) would produce { 50, 50, 50, 55, 50 } — four pixels clip up to the floor. Note that a pixel whose inverted value equals floor is not clipped. Assume 0 <= floor <= 255.

The answer and the full solution open in a window.

Question 43

Free response 2D Arrays

An image-processing routine applies a smoothing filter to a rectangular grid of integer pixel values. For each cell in the input grid, the smoothed grid contains the integer average (truncated toward zero, as with Java's int division) of that cell and its orthogonal neighbors — the cells directly above, below, to the left, and to the right, when they exist.

A corner cell therefore averages three values (itself and its two in-bounds orthogonal neighbors); an edge cell averages four; and an interior cell averages five. Diagonal neighbors are never included. The original grid must not be modified.

Write a static method gridSmooth that takes a rectangular 2-D array grid of non-negative integers (at least one row and one column; every row has the same length) and returns a new 2-D array of the same dimensions containing the smoothed values, as defined above.

Method Signature

public static int[][] gridSmooth(int[][] grid)

Example 1

Given the 3×4 grid on the left, the result is shown on the right. Each cell shows the full computation for reference.

Input gridReturned grid
{ { 4, 8, 12, 0 },
  { 2, 6, 3, 5 },
  { 10, 1, 7, 9 } }
{ { 4, 7, 5, 5 },
  { 5, 4, 6, 4 },
  { 4, 6, 5, 7 } }

For instance, the value at row 1, column 1 is \((6 + 8 + 2 + 3 + 1) / 5 = 20 / 5 = 4\) (itself, up, left, right, down — truncated). The value at row 0, column 0 is \((4 + 8 + 2) / 3 = 14 / 3 = 4\) (itself, right, down — truncated). The value at row 2, column 3 is \((9 + 5 + 7) / 3 = 21 / 3 = 7\).

Example 2

A 1×1 grid maps to itself: gridSmooth({{ 42 }}) returns {{ 42 }} (the sum is 42, divided by 1).

A 1×3 grid behaves as if every cell is on the top and bottom edge: gridSmooth({{ 3, 6, 9 }}) returns {{ 4, 6, 7 }}, since \((3+6)/2 = 4\), \((6+3+9)/3 = 6\), and \((9+6)/2 = 7\).

The answer and the full solution open in a window.

Question 44

Free response 2D Arrays
A rectangular game grid of lights is represented by the partial class LightBoard below. Each entry of the 2D array is true if the light at that position is on…

Sign up now. It's free!

See the full question with its answer and worked solution.

Question 45

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 46

Free response 2D Arrays
A classroom seating arrangement is stored in a class SeatingChart, which uses a two-dimensional String array to hold the name of the student assigned to each…

Sign up now. It's free!

See the full question with its answer and worked solution.

Question 47

Free response 2D Arrays
The TerrainMap class stores a rectangular grid of elevation values in meters. public class TerrainMap { private int[][] height; public TerrainMap(int[][] h) {…

Sign up now. It's free!

See the full question with its answer and worked solution.

Question 48

Free response 2D Arrays
The DeliveryWindow class stores the number of packages delivered during each recorded hour of a day. public class DeliveryWindow { private int[] packages;…

Sign up now. It's free!

See the full question with its answer and worked solution.

Question 49

Free response 2D Arrays
An OrchardGrid object stores fruit counts for trees arranged in a rectangular grid. Each entry in fruit is the number of fruits currently on one tree. public…

Sign up now. It's free!

See the full question with its answer and worked solution.

Question 50

Free response 2D Arrays
This question involves analyzing an orchard of apples to determine how many apple pies can be baked. The orchard is represented as a two-dimensional array of…

Sign up now. It's free!

See the full question with its answer and worked solution.

Question 41 of 50
Page 5 of 5