Implementing 2D Array Algorithms
Standard algorithms on 2D arrays, for the whole grid or a designated row, column, or subsection: minimums, maximums, sums, and averages; property checks and counts; consecutive pairs and duplicates; and shifting, rotating, and reversing within a row or column.
There are standard algorithms that utilize 2D array traversals to determine a minimum or maximum value, compute a sum or average, determine if at least one element or all elements have a particular property, and count the elements having a property, each for the entire 2D array or for a designated row, column, or other subsection. Other standard algorithms access all consecutive pairs of elements, determine the presence or absence of duplicate elements, shift or rotate elements in a row left or right or in a column up or down, and reverse the order of the elements in a row or column.
1Results for the Whole Grid
Every 1D algorithm has a 2D version that runs inside nested loops. To determine a minimum or maximum value of all the elements, start from an actual element, g[0][0], and compare every element with the best so far. Recording the row and column whenever the best changes also gives the location of the minimum or maximum, which is often what a program needs.
To compute a sum or average of all the elements, add every element in a full traversal. The number of elements is the number of rows times the number of columns, g.length * g[0].length. Divide as a double, by casting the sum or the count, so that the average keeps its fractional part.
Maximum, Its Location, and the Average
Predict the output.
int[][] sales = { {12, 7, 9}, {15, 4, 11}, {8, 13, 11} };
int max = sales[0][0];
int maxRow = 0;
int maxCol = 0;
int sum = 0;
for (int r = 0; r < sales.length; r++)
{
for (int c = 0; c < sales[0].length; c++)
{
sum += sales[r][c];
if (sales[r][c] > max)
{
max = sales[r][c];
maxRow = r;
maxCol = c;
}
}
}
int count = sales.length * sales[0].length;
System.out.println("max " + max + " at [" + maxRow + "][" + maxCol + "]");
System.out.println((double) sum / count);
max 15 at [1][0]
10.0
- 1Start from a real element:
sales[0][0]. - 2Record the location along with the value whenever a larger element appears.
- 3Average. The 9 elements sum to 90; casting to
doublebefore dividing gives 10.0.
sum / count with two int values truncates the result. Write (double) sum / count so that the division is done with double values.
2Designated Rows, Columns, and Subsections
Each of these algorithms can also be applied to a designated row, column, or other subsection. For a row, fix the row index and loop over the columns; because a row is a 1D array, an enhanced for loop over g[r] also works. For a column, fix the column index and loop over the rows. Repeating the row computation for every row gives a list of row totals; repeating the column computation gives column totals.
A subsection, such as a rectangle of rows r1 to r2 and columns c1 to c2, uses nested loops whose bounds are the edges of the region instead of the edges of the grid. The body of the loop does not change; only the starting and stopping values do. Every bound must stay inside the grid, or the traversal throws an ArrayIndexOutOfBoundsException.
| Scope | Loop structure |
|---|---|
| Whole 2D array | Nested loops over every row and column (or nested enhanced for) |
| Designated row r | One loop over the columns: g[r][c], or an enhanced for over g[r] |
| Designated column c | One loop over the rows: g[r][c] with c fixed |
| Subsection | Nested loops starting and stopping at the subsection's row and column bounds |
Row Sums and a Column Average
Two methods each traverse a single row or column.
public static int rowSum(int[][] g, int r)
{
int sum = 0;
for (int v : g[r])
{
sum += v;
}
return sum;
}
public static double colAverage(int[][] g, int c)
{
int sum = 0;
for (int r = 0; r < g.length; r++)
{
sum += g[r][c];
}
return (double) sum / g.length;
}
row 0: 28
row 1: 30
row 2: 32
8.0
- 1A row is a 1D array, so
rowSumuses an enhanced for loop overg[r]. - 2A column needs an index loop: fix
cand varyr. Column 1 holds 7, 4, 13: 24 / 3 = 8.0.
Summing a Rectangular Region
Sum the elements from row r1 to r2 and column c1 to c2, inclusive.
public static int regionSum(int[][] g, int r1, int c1, int r2, int c2)
{
int sum = 0;
for (int r = r1; r <= r2; r++)
{
for (int c = c1; c <= c2; c++)
{
sum += g[r][c];
}
}
return sum;
}
31
32
- 1Rows 0 to 1, columns 1 to 2: 7 + 9 + 4 + 11 = 31.
- 2A single row is also a region: row 2, columns 0 to 2, sums to 32.
- 3Inclusive bounds use
<=; the caller must pass indices inside the grid.
When a subsection is described as "rows 1 to 2, inclusive", the loop condition is r <= 2; when it is described by a starting index and a number of rows, the condition is r < start + count. Decide which description is being used before writing the loop, and check the last index the loop reaches.
3Checking Properties
Determining if at least one element has a particular property, in the entire 2D array or a designated part, returns true as soon as one matching element is found and false only after the traversal ends. Determining if all elements have a property does the opposite: return false at the first failure and true after the traversal. Counting the elements with a property adds 1 for every match and never stops early.
Writing each check as a method with parameters, such as the grid, a row or column index, and a limit, makes the code reusable for every row or column and keeps the early return statements clear.
Any, All, and How Many
Predict the output.
public static int countOver(int[][] g, int limit)
{
int count = 0;
for (int[] row : g)
{
for (int v : row)
{
if (v > limit)
{
count++;
}
}
}
return count;
}
public static boolean anyBelowInColumn(int[][] g, int c, int limit)
{
for (int r = 0; r < g.length; r++)
{
if (g[r][c] < limit)
{
return true;
}
}
return false;
}
public static boolean allAtLeastInRow(int[][] g, int r, int min)
{
for (int v : g[r])
{
if (v < min)
{
return false;
}
}
return true;
}
5
true
true
- 1Count in the whole grid. 12, 15, 11, 13, and 11 exceed 10: 5.
- 2At least one in a column. Column 1 contains 4, which is below 5:
trueas soon as it is found. - 3All in a row. Row 2 is 8, 13, 11, all at least 8:
trueonly after checking every element.
4Consecutive Pairs and Duplicates
Accessing all consecutive pairs of elements in a 2D array usually means neighbors along a row, g[r][c] and g[r][c + 1], or down a column, g[r][c] and g[r + 1][c]. The index that moves stops one before its last value so that the neighbor exists. Pair algorithms count rises and falls, check whether rows are in order, or find the largest difference between neighbors.
Determining the presence or absence of duplicate elements compares elements with one another. For a single row or column, nested loops with the inner index starting one past the outer index work exactly as for a 1D array. For the whole grid, a helper method that counts how many times a value occurs keeps the code readable: any value whose count is greater than 1 is a duplicate.
Rises Within Each Row
Count how many times a value is larger than the one to its left.
int[][] sales = { {12, 7, 9}, {15, 4, 11}, {8, 13, 11} };
int rises = 0;
for (int r = 0; r < sales.length; r++)
{
for (int c = 0; c < sales[0].length - 1; c++)
{
if (sales[r][c + 1] > sales[r][c])
{
rises++;
}
}
}
System.out.println(rises);
3
- 1Inner bound.
c < sales[0].length - 1so thatc + 1is always a valid column. - 2Pairs. Row 0: 7→9 rises. Row 1: 4→11 rises. Row 2: 8→13 rises. The other pairs fall.
Does Any Value Appear Twice?
A helper counts occurrences; a value that occurs more than once is a duplicate.
public static int countOf(int[][] g, int target)
{
int count = 0;
for (int[] row : g)
{
for (int v : row)
{
if (v == target)
{
count++;
}
}
}
return count;
}
public static boolean hasDuplicate(int[][] g)
{
for (int[] row : g)
{
for (int v : row)
{
if (countOf(g, v) > 1)
{
return true;
}
}
}
return false;
}
true
2
- 1Every element counts itself once, so a count greater than 1 means another element holds the same value.
- 211 appears twice (row 1 and row 2), so
hasDuplicatereturnstrue.
5Shifting and Rotating in a Row or Column
Shifting moves elements in a row left or right, or in a column up or down, by one position. A rotation also wraps the element that falls off one end around to the other end; a plain shift instead fills the vacated position with a placeholder. Because arrays cannot grow, both operations copy values from cell to cell, and the order of copying matters.
To shift right, copy from the end toward the beginning, so that each value is read before its cell is overwritten; to shift left or up, copy from the beginning. For a rotation, save the element that would be lost in a temporary variable before the copying starts, then store it in the vacated position at the end.
| Step | Statement | Row 0 afterward |
|---|---|---|
| start | 12 7 9 | |
| 1 | last = row[2] | 12 7 9 (last = 9) |
| 2 | row[2] = row[1] | 12 7 7 |
| 3 | row[1] = row[0] | 12 12 7 |
| 4 | row[0] = last | 9 12 7 |
Right by One, From the End
Rotate row 0 one place to the right (Figure 3).
int[][] sales = { {12, 7, 9}, {15, 4, 11}, {8, 13, 11} };
int[] row = sales[0];
int last = row[row.length - 1];
for (int c = row.length - 1; c > 0; c--)
{
row[c] = row[c - 1];
}
row[0] = last;
System.out.println(sales[0][0] + " " + sales[0][1] + " " + sales[0][2]);
9 12 7
- 1
rowrefers tosales[0], so changes throughrowchange the 2D array. - 2Save the last element before it is overwritten.
- 3Shift from the end backward, so each value is copied before its cell is reused; then store
lastat index 0.
Moving Values Up and Filling the Gap
Shift column 2 up by one without wrapping; the bottom becomes 0.
int[][] sales = { {12, 7, 9}, {15, 4, 11}, {8, 13, 11} };
int c = 2;
for (int r = 0; r < sales.length - 1; r++)
{
sales[r][c] = sales[r + 1][c];
}
sales[sales.length - 1][c] = 0;
System.out.println(sales[0][c] + " " + sales[1][c] + " " + sales[2][c]);
11 11 0
- 1Shifting up copies each element from the row below, working from the top down, so nothing is overwritten before it is copied.
- 2The vacated bottom cell receives a placeholder, 0, since a shift without wrapping drops the top value.
A loop that copies row[c + 1] = row[c] starting at c = 0 copies the first value into every cell, because each cell is overwritten before its value is moved. Shift right by starting at the end and moving backward.
6Reversing a Row or Column
Reversing the order of the elements in a row or column swaps pairs from both ends toward the middle, using a temporary variable for each swap. For a column, only the row index changes: element i swaps with element g.length - 1 - i, for i less than g.length / 2. In a row or column of odd length, the middle element stays in place.
Stopping at the halfway point is essential. A loop that runs over the whole column swaps each pair twice and leaves the column exactly as it started, a bug that is easy to miss because the code produces no error.
Swapping Top and Bottom
Reverse column 0 (Figure 4).
int[][] sales = { {12, 7, 9}, {15, 4, 11}, {8, 13, 11} };
int c = 0;
for (int i = 0; i < sales.length / 2; i++)
{
int j = sales.length - 1 - i;
int temp = sales[i][c];
sales[i][c] = sales[j][c];
sales[j][c] = temp;
}
for (int r = 0; r < sales.length; r++)
{
System.out.println(sales[r][c]);
}
8
15
12
- 1Only the row index changes; the column stays at
c. - 2
sales.length / 2is 1, so one swap happens: rows 0 and 2.
| Algorithm | 2D approach |
|---|---|
| Minimum or maximum | Start at g[0][0] (or the first element of the row/column); compare every element |
| Sum or average | Add elements; divide by the number of elements as a double |
| At least one / all / how many | Return early for a match (any) or a failure (all); count otherwise |
| Consecutive pairs | Compare g[r][c] with g[r][c + 1] (or g[r + 1][c]) |
| Duplicates | Compare each element with the others, for example by counting occurrences |
| Shift or rotate a row or column | Save the element that would be lost; copy in the safe direction |
| Reverse a row or column | Swap pairs from both ends toward the middle |
If the swap loop runs to the end of the row or column instead of the middle, every pair is swapped back and the data ends up unchanged. Bound the loop by half the length.
Four Habits for 2D Algorithms
1. Name the Scope
Whole grid, row, column, or subsection.
2. Fix One Index
For a single row or column.
3. Copy in the Safe Direction
Save what would be lost first.
4. Stop at the Middle
When reversing by swaps.
There are standard algorithms that utilize 2D array traversals to determine a minimum or maximum value of all the elements or for a designated row, column, or other subsection; compute a sum or average of all the elements or for a designated row, column, or other subsection; determine if at least one element has a particular property in the entire 2D array or a designated part; determine if all elements of the 2D array or a designated part have a particular property; determine the number of elements having a particular property; access all consecutive pairs of elements; determine the presence or absence of duplicate elements in the 2D array or a designated part; shift or rotate elements in a row left or right or in a column up or down; and reverse the order of the elements in a row or column.