Java Reference
In-Depth Information
If we number both the rows and the entries in each row beginning with 0, the entry in position
k
of row
n
is
often denoted as
C
(
n
,
k
). For example, the 6 in the last row is
C
(4, 2). Given
n
items,
C
(
n
,
k
) turns out to be the
number of ways that you can select
k
of the
n
items. Thus,
C
(4, 2), which is 6, is the number of ways that you can
select two of four given items. So if A, B, C, and D are the four items, here are the six possible choices:
A B, A C, A D, B C, B D, C D
Note that the order of the items in each pair is irrelevant. For instance, the choice A B is the same as the choice B A.
Design and implement the class
PascalTriangle
. Represent each row in a triangle as a list and the entire tri-
angle as a list of these lists. Use the class
ArrayList
for these lists. Give your class constructors and at least the
method
getChoices(n, k)
, which returns the integer value of
C
(
n
,
k
).
A
NSWERS
TO
S
ELF
-T
EST
Q
UESTIONS
1.
myList.add(c)
myList.add(1, a)
myList.add(2, b)
myList.add(4, d)
2.
seven = myList.remove(7)
three = myList.remove(3)
myList.add(3, seven)
myList.add(7, three)
Another solution:
seven = myList.getEntry(7)
three = myList.getEntry(3)
myList.replace(3, seven)
myList.replace(7, three)
3.
ListInterface<Integer> rList =
new
AList<Integer>();
rList.add(16);
rList.add(4);
rList.add(33);
rList.add(27);
rList.displayList();
4.
bob = alphaList.remove(3);
ellen = alphaList.remove(2);
alphaList.add(2, bob);
alphaList.add(3, ellen);
drew = alphaList.remove(4);
ellen = alphaList.remove(3);
alphaList.add(3, drew);
alphaList.add(4, ellen);
Another solution uses
getEntry
and
replace
, much like the second solution to Question 2.
5.
The change to
getEntry
would affect its use by requiring a cast to the type of entry retrieved. Thus, you would write
Name secondName = (Name)nameList.getEntry(2);
A similar statement without the type cast would be incorrect. A reference to
Object
cannot be assigned to a
Name
variable without a cast.