Solutions to other chapters:
Java Methods A & AB:
Object-Oriented Programming and Data Structures
Answers and Solutions to Exercises
Chapter 12
1. |
(a) |
int a[] = {1, 2, 4}; |
2. |
(a) |
F |
|
(c) |
T |
|
(d) |
F -- in arrays, length is not a method but works like a public
field. |
3. |
|
public void swapFirstLast(int[] a)
{
int i = a.length - 1;
if (i > 0)
{
int temp = a[0];
a[0] = a[i];
a[i] = temp;
}
} |
5. |
|
public char getRandomRps()
{
char[] rps =
{'r', 'r', 'r', 'p', 'p', 'p', 'p', 'p',
's', 's', 's', 's', 's', 's'};
int i = (int)(Math.random() * rps.length);
return rps[i];
}
|
12. |
|
public ArrayList reverse(ArrayList list)
{
ArrayList reversed = new ArrayList(list.size());
for (int i = list.size() - 1; i >= 0; i--)
reversed.add(list.get(i));
return reversed;
} |
20. |
|
public static double averageTopTwo(int[] scores)
{
int i, n = scores.length;
int iMax1 = 0; // index of the largest element
int iMax2 = 1; // index of the second largest element
// if scores[iMax2] is bigger than scores[iMax1] --
// swap iMax1 and iMax2
if (scores[iMax2] > scores[iMax1])
{
i = iMax1;
iMax1 = iMax2;
iMax2 = i;
}
for (i = 2; i < n; i++)
{
if (scores[i] > scores[iMax1])
{
iMax2 = iMax1;
iMax1 = i;
}
else if (scores[i] > scores[iMax2] )
{
iMax2 = i;
}
}
return (double)(scores[iMax1] + scores[iMax2]) / 2;
} |
22. |
|
private static int[] add(int[] a, int[] b)
{
int[] sum = new int[N];
int carry = 0;
for (int i = N-1; i >= 0; i--)
{
int d = a[i] + b[i] + carry;
sum[i] = d % 10;
carry = d / 10;
}
return sum;
} |
24. |
|
i == j || i + j == n - 1 |
25. |
|
private static double positiveMax(double[][] m)
{
double mMax = 0;
int rows = m.length, cols = m[0].length;
for (int r = 0; r < rows; r++)
for (int c = 0; c < cols; c++)
if (m[r][c] > mMax)
mMax = m[r][c];
return mMax;
} |
27. |
|
private static boolean covers(double[][] m1, double[][] m2)
{
int count = 0;
for (int r = 0; r < m1.length; r++)
for (int c = 0; c < m1[0].length; c++)
if (m1[r][c] > m2[r][c])
count++;
return 2 * count >= nRows * nCols;
// return count >= nRows * nCols / 2 doesn't work,
// for example, nRows = 3, nCols = 3, count = 4
} |
29. |
(c) |
Passing a name as a parameter to HumanPlayer 's constructor is
more flexible than coding specific names in different subclasses.
It also reduces the number of classes.
From the object-oriented design point of view, it is more appropriate to
treat a name of a player as an attribute of an object, rather than its type. |
|