Grade 12 Computer Science · Two-dimensional arrays

The standard grid patterns

How the five patterns from grade eleven look in two dimensions.

One total or a total per row: one line moves

Exactly the same two loops can compute one total for the whole grid, or a separate total for each row. Between the two versions there is no new loop and no new condition, only one line moved somewhere else. Which line, and where to?

The five patterns you learned on an array — accumulate, count, extreme, search, filter — work on a grid in exactly the same way. What is added is at which level one accumulates: over the whole structure, or one result per row.

// one total for everything
int total = 0;
for (int[] row : grid)
    for (int v : row) total += v;

// one total per row
for (int[] row : grid) {
    int rowTotal = 0;              // inside the outer loop
    for (int v : row) rowTotal += v;
    System.out.println(rowTotal);
}

A search that returns a position

One pattern changes more than the others. In an array, a search returns one position; in a grid it must return two — a row and a cell. The three accepted ways: return a small array of two numbers, return a small object with two fields, or keep them in two fields and return whether it was found. The second is the most readable of all, because the field names say what each number is, and the first is the one you will see most.

The patternWhat changes in a grid
AccumulationWhere the initialisation line sits
CountingWhere the initialisation line sits
An extremeWhere the initialisation line sits
SearchReturns two numbers and not one

Example 1 — why the initialisation line decides

  1. Outside — it runs once.
  2. Inside — it runs on every row.
  3. And that is the whole difference between the levels.

Example 2 — why a search needs two numbers

  1. A cell is identified by a row and a position in it.
  2. One number does not suffice.
  3. So one must decide how to return two.
In both accumulations the loops are identical; only the initialization line moves.