Java Reference
In-Depth Information
**7.6
(
Algebra: multiply two matrices
) Write a method to multiply two matrices. The
header of the method is:
public static double
[][]
multiplyMatrix(
double
[][] a,
double
[][] b)
To multiply matrix
a
by matrix
b
, the number of columns in
a
must be the same as
the number of rows in
b
, and the two matrices must have elements of the same or
compatible types. Let
c
be the result of the multiplication. Assume the column size
of matrix a is
n
. Each element
c
ij
is
a
i
1
*
b
1
j
+
a
i
2
*
b
2
j
+
c
+
a
in
*
b
nj
.
For example, for two
3
*
3
matrices
a
and
b
,
c
is
a
11
a
12
a
13
b
11
b
12
b
13
c
11
c
12
c
13
£
a
21
a
22
a
23
a
33
≥ * £
b
21
b
22
b
23
b
33
≥ = £
c
21
c
22
c
23
c
33
≥
a
31
a
32
b
31
b
32
c
31
c
32
where
Write a test program that prompts the user to enter two
c
ij
=
a
i
1
*
b
1
j
+
a
i
2
*
b
2
j
+
a
i
3
*
b
3
j
.
3
*
3
matrices and displays
their product. Here is a sample run:
Enter matrix1:
Enter matrix2:
The multiplication of the matrices is
1 2 3 0 2.0 4.0 5.3 23.9 24
4 5 6 * 1 4.5 2.2 = 11.6 56.3 58.2
7 8 9 1.1 4.3 5.2 17.9 88.7 92.4
1 2 3 4 5 6 7 8 9
0 2 4 1 4.5 2.2 1.1 4.3 5.2
*7.7
(
Points nearest to each other
) Listing 7.3 gives a program that finds two points
in a two-dimensional space nearest to each other. Revise the program so that it
finds two points in a three-dimensional space nearest to each other. Use a two-
dimensional array to represent the points. Test the program using the following
points:
double
[][] points = {{
-1
,
0
,
3
}, {
-1
,
-1
,
-1
}, {
4
,
1
,
1
},
{
2
,
0.5
,
9
}, {
3.5
,
2
,
-1
}, {
3
,
1.5
,
3
}, {
-1.5
,
4
,
2
},
{
5.5
,
4
,
-0.5
}};
The formula for comp
uting the distance between two points
(x1, y1, z1)
and
(x2, y2, z2)
is
x
1
)
2
y
1
)
2
z
1
)
2
.
2
(
x
2
-
+
(
y
2
-
+
(
z
2
-
**7.8
(
All closest pairs of points
) Revise Listing 7.3, FindNearestPoints.java, to find all
closest pairs of points with the same minimum distance.
***7.9
(
Game: play a tic-tac-toe game
) In a game of tic-tac-toe, two players take turns
marking an available cell in a grid with their respective tokens (either X or O).
When one player has placed three tokens in a horizontal, vertical, or diagonal row on
the grid, the game is over and that player has won. A draw (no winner) occurs when
all the cells on the grid have been filled with tokens and neither player has achieved
a win. Create a program for playing tic-tac-toe.
The program prompts two players to enter an X token and O token alternately.
Whenever a token is entered, the program redisplays the board on the console and
determines the status of the game (win, draw, or continue). Here is a sample run:
3
*
3