Java Reference
In-Depth Information
grid[0][6]
grid[0][0]
For any grid[i][j] in this 3 by 3 box, its starting cell
is grid[3*(i/3)][3*(j/3)] (i.e., grid[0][6]). For
example, for grid[2][8], i=2 and j=8, 3*(i/3)=0 and
3*(j/3)=6.
grid[6][3]
For any grid[i][j] in this 3 by 3 box, its
starting cell is grid[3*(i/3)][3*(j/3)]
(i.e., grid[6][3]). For example, for
grid[8][5], i=8 and j=5, 3*(i/3)=6 and
3*(j/3)=3.
F
IGURE
8.7
The location of the first cell in a 3
*
3 box determines the locations of other cells in the box.
With this observation, you can easily identify all the cells in the box. For instance, if
grid[r][c]
is the starting cell of a 3
*
3 box, the cells in the box can be traversed in a
nested loop as follows:
// Get all cells in a 3-by-3 box starting at grid[r][c]
for
(
int
row = r; row < r +
3
; row++)
for
(
int
col = c; col < c +
3
; col++)
// grid[row][col] is in the box
It is cumbersome to enter 81 numbers from the console. When you test the program, you
may store the input in a file, say
CheckSudokuSolution.txt
(see
www.cs.armstrong.edu/liang/
data/CheckSudokuSolution.txt
),
and run the program using the following command:
input file
java CheckSudokuSolution < CheckSudokuSolution.txt
A two-dimensional array consists of an array of one-dimensional arrays and a three-
dimensional array consists of an array of two-dimensional arrays.
Key
Point
In the preceding section, you used a two-dimensional array to represent a matrix or a table.
Occasionally, you will need to represent
n
-dimensional data structures. In Java, you can create
n
-dimensional arrays for any integer
n
.
The way to declare two-dimensional array variables and create two-dimensional arrays can
be generalized to declare
n
-dimensional array variables and create
n
-dimensional arrays for
n
3. For example, you may use a three-dimensional array to store exam scores for a class
of six students with five exams, and each exam has two parts (multiple-choice and essay). The
following syntax declares a three-dimensional array variable
scores
, creates an array, and
assigns its reference to
scores
.
7 =
double
[][][] scores =
new double
[
6
][
5
][
2
];
You can also use the short-hand notation to create and initialize the array as follows:
double
[][][] scores = {
{{
7.5
,
20.5
}, {
9.0
,
22.5
}, {
15
,
33.5
}, {
13
,
21.5
}, {
15
,
2.5
}},
{{
4.5
,
21.5
}, {
9.0
,
22.5
}, {
15
,
34.5
}, {
12
,
20.5
}, {
14
,
9.5
}},
{{
6.5
,
30.5
}, {
9.4
,
10.5
}, {
11
,
33.5
}, {
11
,
23.5
}, {
10
,
2.5
}},
{{
6.5
,
23.5
}, {
9.4
,
32.5
}, {
13
,
34.5
}, {
11
,
20.5
}, {
16
,
7.5
}},
{{
8.5
,
26.5
}, {
9.4
,
52.5
}, {
13
,
36.5
}, {
13
,
24.5
}, {
16
,
2.5
}},
{{
9.5
,
20.5
}, {
9.4
,
42.5
}, {
13
,
31.5
}, {
12
,
20.5
}, {
16
,
6.5
}}};
Search WWH ::
Custom Search