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 pattern | What changes in a grid |
|---|---|
| Accumulation | Where the initialisation line sits |
| Counting | Where the initialisation line sits |
| An extreme | Where the initialisation line sits |
| Search | Returns two numbers and not one |
Example 1 — why the initialisation line decides
- Outside — it runs once.
- Inside — it runs on every row.
- And that is the whole difference between the levels.
Example 2 — why a search needs two numbers
- A cell is identified by a row and a position in it.
- One number does not suffice.
- So one must decide how to return two.