(^586) | Multidimensional Arrays and Numeric Computation
From the Java programmer’s perspective, however, the two views are synonymous in the
majority of applications. We typically instantiate arrays with the same number of columns in
every row, rarely creating a ragged array. For this reason, we continue to use the stylized version.
12.2 Processing Two-Dimensional Arrays
Processing data in a two-dimensional array generally means accessing the array in one of
four patterns: randomly, along rows, along columns, or throughout the entire array. Each of
these strategies may also involve subarray processing.
The simplest way to access a component is to look directly in a given location. For ex-
ample, a user might enter map coordinates that we use as indexes into an array of street
names to access the desired name at those coordinates. This process is referred to as random
accessbecause the user may enter any set of coordinates at random.
In many cases, we might want to perform an operation on all the elements of a particu-
lar row or column in an array. Consider thehiTemparray defined previously, in which the rows
represent weeks of the year and the columns represent days of the week. If we wanted the
average high temperature for a given week, we would sum the values in that row and divide
by 7. If we wanted the average for a given day of the week, we would sum the values in that
column and divide by 52.The former case is access by row; the latter case is access by column.
Now suppose that we want to determine the average high temperature for the year. We
must access every element in the array, sum them, and divide by 364. In this case, the order
of access—by row or by column—is not important. (The same is true when we initialize
every element of an array to some constant, such as 1.) This approach involves access
throughout the array.
Sometimes, however, we must access every array element in a particular order, either by
rows or by columns. For example, if we wanted the average high temperature for every week,
we would run through the entire array, taking each row in turn. However, if we wanted the
average high temperature for each day of the week, we would run through the array one
column at a time.
Let’s take a closer look at these patterns of access by considering three common exam-
ples of array processing:
1.Sum the rows.
2.Sum the columns.
3.Initialize the array to all zeros (or some special value).
In the following discussion, we use the generic identifiers rowand col, rather than prob-
lem-dependent identifiers, and look at each algorithm in terms of generalized two-dimen-
sional array processing. The array that we use is declared and instantiated by the following
statement:
int[][] data = new int[50][30]; // A two-dimensional array
In the following discussion we assume that datacontains valid information.