ACSA Exam Prep
Unit 4 · Data Collections · Topic 4.13

Implementing 2D Array Algorithms

Skill 2.BSkill 3.BSkill 3.DSkill 4.A

Big idea: The 1D algorithms work on the whole grid, one row, one column, or a region. FRQ 4 asks you to write one of these.

Learning objectives
  • Develop code for standard and original algorithms for a particular context or specification that involves 2D arrays and determine the result of these algorithms.

Row sums and column max

Code
int[][] g = { {3, 9, 1}, {7, 2, 8} };
for (int r = 0; r < g.length; r++) {
  int sum = 0;
  for (int c = 0; c < g[r].length; c++) sum += g[r][c];
  System.out.print(sum + " ");
}
System.out.println();
int col = 2;
int max = g[0][col];
for (int r = 1; r < g.length; r++) {
  if (g[r][col] > max) max = g[r][col];
}
System.out.println(max);
Output
13 17
8

Neighbors with a bounds check

Before looking at g[r][c + 1] or g[r - 1][c], make sure the index exists.

Code
int[][] g = { {1, 5, 2}, {6, 3, 4} };
int peaks = 0;
for (int r = 0; r < g.length; r++) {
  for (int c = 0; c < g[0].length; c++) {
    boolean higher = true;
    if (c > 0 && g[r][c - 1] >= g[r][c]) higher = false;
    if (c < g[0].length - 1 && g[r][c + 1] >= g[r][c]) higher = false;
    if (higher) peaks++;
  }
}
System.out.println(peaks);
Output
3

Building a new 2D array

Code
int[][] g = { {1, 2, 3}, {4, 5, 6} };
int[][] t = new int[g[0].length][g.length];
for (int r = 0; r < g.length; r++) {
  for (int c = 0; c < g[0].length; c++) {
    t[c][r] = g[r][c];
  }
}
for (int[] row : t) System.out.println(Arrays.toString(row));
Output
[1, 4]
[2, 5]
[3, 6]
Key points
  • Apply min/max, sum/average, any/all, count, consecutive pairs, duplicates, shift/rotate, and reverse to the whole grid or to a row, column, or region.
Watch out
  • Check bounds before looking at a neighbor cell, or you'll index off the edge.
Exam tip
  • For quick tracing, check what happens to the top-left and bottom-right cells. That often rules out most choices.
Quick check
Which loop bound visits every column of row r?
Show answer
c < g[r].length (or g[0].length for a rectangular array).