๐4.13: 2D Array Algorithms
Table of Contents
๐ This page is a condensed version of CSAwesome Topic 4.13
2D Array Algorithms
All of the array algorithms can be applied to 2D arrays too. For example, counting and searching algorithms work very similarly.
๐งฎ Counting/Accumulating
Method Definition:
public static int getTotalForRow(int row, int[][] a) {
int total = 0;
for (int col = 0; col < a[0].length; col++) {
total = total + a[row][col];
}
return total;
}
Method Call (in main):
public static void main(String[] args) {
int[][] matrix = { {1, 2, 3}, {4, 5, 6}};
System.out.println(getTotalForRow(0, matrix));
}
๐ป Can you complete the method called getTotalForCol that computes the total for a column? To do this, you must loop through the rows. The arrayโs length will tell you how many rows you have, while the length of the arrayโs first element will tell you how many columns.
public static int getTotalForCol(int col, int[][] a) {
int total = 0;
// Add a loop here to total a column col
return total;
}
๐ Linear Search
The linear (sequential) search algorithm for a 2D array iterates through all of the rows and columns until either the target value is found, or the entire 2D array has been traversed without finding the target.
Method Definition:
public static boolean search(int[][] array, int value) {
boolean found = false;
for (int row = 0; row < array.length; row++) {
for (int col = 0; col < array[0].length; col++) {
if (array[row][col] == value) {
found = true;
}
}
}
return found;
}
Method Call (in main):
public static void main(String[] args) {
int[][] matrix = { {3, 2, 3}, {4, 3, 6}, {8, 9, 3}, {10, 3, 3}};
System.out.println(search(matrix, 10));
System.out.println(search(matrix, 11));
}
๐ป Can you change the methodโs code to work for a String 2D array instead of an int array? Note that the indices row and col will still be integers.
// In the MAIN method, try these:
String[][] matrix2 = { {"a","b","c"},{"d","e","f"} };
System.out.println(search(matrix2, "b"));
Acknowledgement
Content on this page is adapted from Runestone Academy - Barb Ericson, Beryl Hoffman, Peter Seibel.