Java Reference
In-Depth Information
4.
Summing all elements.
Use a variable named
total
to store the sum. Initially
total
is
0
. Add each element in the array to
total
using a loop like this:
int
total =
0
;
for
(
int
row =
0
; row < matrix.length; row++) {
for
(
int
column =
0
; column < matrix[row].length; column++) {
total += matrix[row][column];
}
}
5.
Summing elements by column.
For each column, use a variable named
total
to store
its sum. Add each element in the column to
total
using a loop like this:
for
(
int
column =
0
; column < matrix[
0
].length; column++) {
int
total =
0
;
for
(
int
row =
0
; row < matrix.length; row++)
total += matrix[row][column];
System.out.println(
"Sum for column "
+ column +
" is "
+ total);
}
6.
Which row has the largest sum?
Use variables
maxRow
and
indexOfMaxRow
to track
the largest sum and index of the row. For each row, compute its sum and update
maxRow
and
indexOfMaxRow
if the new sum is greater.
int
maxRow =
0
;
int
indexOfMaxRow =
0
;
VideoNote
Find the row with the largest
sum
// Get sum of the first row in maxRow
for
(
int
column =
0
; column < matrix[
0
].length; column++) {
maxRow += matrix[
0
][column];
}
for
(
int
row =
1
; row < matrix.length; row++) {
int
totalOfThisRow =
0
;
for
(
int
column =
0
; column < matrix[row].length; column++)
totalOfThisRow += matrix[row][column];
if
(totalOfThisRow > maxRow) {
maxRow = totalOfThisRow;
indexOfMaxRow = row;
}
}
System.out.println(
"Row "
+ indexOfMaxRow
+
" has the maximum sum of "
+ maxRow);
7.
Random shuffling.
Shuffling the elements in a one-dimensional array was introduced in
Section 6.2.6. How do you shuffle all the elements in a two-dimensional array? To
accomplish this, for each element
matrix[i][j]
, randomly generate indices
i1
and
j1
and swap
matrix[i][j]
with
matrix[i1][j1]
, as follows:
for
(
int
i =
0
; i < matrix.length; i++) {
for
(
int
j =
0
; j < matrix[i].length; j++) {
int
i1 = (
int
)(Math.random() * matrix.length);
int
j1 = (
int
)(Math.random() * matrix[i].length);
// Swap matrix[i][j] with matrix[i1][j1]
int
temp = matrix[i][j];
matrix[i][j] = matrix[i1][j1];
matrix[i1][j1] = temp;
}
}