Verityprep
Question Bank

AP® Computer Science A Practice Questions

Work through AP Computer Science A practice questions unit by unit, 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 3,071–3,080 of 3,140
  1. 3071
  2. 3072
  3. 3073
  4. 3074
  5. 3075
  6. 3076
  7. 3077
  8. 3078
  9. 3079
  10. 3080

Question 3071

Free response Unit 4: Data Collections

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 3072

Multiple choice Unit 4: Data Collections
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 3073

Multiple choice Unit 4: Data Collections
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 3074

Multiple choice Unit 4: Data Collections
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 3075

Multiple choice Unit 4: Data Collections
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 3076

Multiple choice Unit 4: Data Collections
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 3077

Multiple choice Unit 4: Data Collections
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 3078

Multiple choice Unit 4: Data Collections
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 3079

Multiple choice Unit 4: Data Collections
Consider the following class. public class Reading { private String sensor; private double value; public Reading(String s, double v) { sensor = s; value = v; }…

Sign up now. It's free!

See the full question with its answer and worked solution.

Question 3080

Free response Unit 4: Data Collections
A weather station records the rainfall, in millimetres, that fell during each day of an observation period. The class RainfallLog stores these daily…

Sign up now. It's free!

See the full question with its answer and worked solution.

Question 3,071 of 3,140
Page 308 of 314