Data Structures and Java Collection Framework - William Collins - Chapter 10 Solutions

CONCEPT EXERCISES

10.1 a. Show the effect of making the following insertions into an initially empty binary search tree:
30, 40, 20, 90, 10, 50, 70, 60, 80
b. Find a different ordering of the above elements whose insertions would generate the same binary search
tree as in part a. Get the solution of 10.1


10.2 Describe in English how to remove each of the following from a binary search tree:
a. an element with no children
b. an element with one child
c. an element with two children Get the solution of 10.2


10.3 a. For any positive integer n, describe how to arrange the integers 1,2, . . . , n so that when they are inserted into a BinarySearchTree object, the height of the tree will be linear in n.
b. For any positive integer n, describe how to arrange the integers 1,2, . . . , n so that when they are inserted into a BinarySearchTree object, the height of the tree will be logarithmic in n.
c. For any positive integer n, describe how to arrange the integers 1,2, . . . , n so that when they are inserted into an AVLTree object, the height of the tree will be logarithmic in n.
d. For any positive integer n, is it possible to arrange the integers 1,2, . . . , n so that when they are inserted into an AVLTree object, the height of the tree will be linear in n? Explain. Get the solution of 10.3


10.4 In each of the following binary search trees, perform a left rotation around 50.

 

10.5 In each of the following binary search trees, perform a right rotation around 50.



10.6 In the following binary search tree, perform a double rotation (a left rotation around 20 and then a right rotation around 50) to reduce the height to 2.

 10.7 In the following binary search tree, perform a “double rotation” to reduce the height to 2:



10.9 Suppose we define maxh to be the maximum number of elements in an AVL tree of height h.
a. Calculate max3.
b. Determine the formula for maxh for any h ≥ 0.
Hint: Use the Binary Tree Theorem from Chapter 9.
c. What is the maximum height of an AVL tree with 100 elements? Get the solution of 10.9


10.10 Show that the height of an AVL tree with 32 elements must be exactly 5.
Hint: calculate max4 (see Concept Exercise 10.9) and min6. Get the solution of 10.10


10.11 For the contains method in the BinarySearchTree class, worstTime(n) is linear in n. The AVLTree class does not override that method, but for the contains method in the AVLTree class, worstTime(n) is logarithmic in n. Explain. Get the solution of 10.11

10.12 The following program generates a BinarySearchTree object of n elements. Draw the tree when
n = 13. For any n ≥ 0, provide a ! (that is, Big Theta) estimate of height(n), that is, the height of the
BinarySearchTree object as a function of n.
import java.util.*;
public class weirdBST
{
public static void main (String[] args)
{
new weirdBST().run();
} // method main
public void run()
{
BinarySearchTree<Double> tree = new BinarySearchTree<Double>();
LinkedList<Double> list =new LinkedList<Double>();
System.out.println ("Enter n > 0");
int n = new Scanner (System.in).nextInt();
tree.add (1.0);
list.add (1.0);
int k = 2;
while (tree.size() < n)
addLevel (tree, n, k++, list);
System.out.println (tree.height());
} // method run
public void addLevel (BinarySearchTree<Double> tree, int n, int k,
LinkedList<Double> list)
{
final double SMALL = 0.00000000001;
LinkedList<Double> newList = new LinkedList<Double>();
Iterator<Double> itr = list.iterator();
double d = itr.next();
tree.add (d - 1.0);
newList.add (d - 1.0);
for (int i = 0; i < k && tree.size() < n; i++)
{
tree.add (d + SMALL );
newList.add (d + SMALL);
if (itr.hasNext())
d = itr.next();
} // for
list.clear();
list.addAll (newList);
} // method addLevel
} // class weirdBST  Get the solution of 10.12

PROGRAMMING EXERCISES
10.1 In the BinarySearchTree class, test and develop a leaves method. Here is the method specification:
/**
* Returns the number of leaves in this BinarySearchTree object.
* The worstTime(n) is O(n).
*
* @return – the number of leaves in this BinarySearchTree object.
*
*/
public int leaves()
Test your method by adding tests to the BinarySearchTreeTest class available from the book’s website.
Hint: A recursive version, invoked by a wrapper method, can mimic the definition of leaves(t) from Section 9.1. Or, you can also develop an iterative version by creating a new iterator class in which the next method increments a count for each Entry object whose left and right fields are null. Get the solution of 10.1


10.2 Modify the BinarySearchTree class so that the iterators are fail-fast (see Appendix 1 for details on fail-fast iterators). Test your class by adding tests to the BinarySearchTreeTest class available from
the book’s website. Get the solution of 10.2


10.3 Modify the BinarySearchTree class so that BinarySearchTree objects are serializable (see
Appendix 1 for details on serializability). Test your class by adding tests to the BinarySearchTreeTest
class available from the book’s website. Get the solution of 10.3


10.4 Create a recursive version of the add method.
Hint: Make the add method a wrapper for a recursive method. Test your version with the relevant tests in the BinarySearchTreeTest class available from the book’s website. Get the solution of 10.4


10.5 In the BinarySearchTree class, modify the getEntry method so that it is a wrapper for a recursive
method. Test your version with the relevant tests in the BinarySearchTreeTest class available from
the book’s website. Get the solution of 10.5


10.6 (This exercise assumes you have completed Programming Projects 10.3 and 10.4.) Create a test suite for the AVLTree class.
Hint: Make very minor modifications to the BinarySearchTreeTest class available from the book’s
website. Use your test suite to increase your confidence in the correctness of the methods you defined in Programming Projects 10.3 and 10.4.
10.7 (This exercise assumes you have completed Programming Projects 10.3 and 10.4.) In the AVLTree class,
test and define the following method:
/**
* The height of this AVLTree object has been returned.
* The worstTime(n) is O(log n).

*
* @return the height of this AVLTree object.
*
*/
public int height()
Hint: Use the balanceFactor field in the AVLEntry class to guide you down the tree. Test your method
by adding tests to the BinarySearchTreeTest class available from the book’s website. Get the solution of 10.6

Data Structures and Java Collection Framework - William Collins - Chapter 9 Solutions

CONCEPT EXERCISES

9.1 Answer the questions below about the following binary tree:


a. What is the root element?
b. How many elements are in the tree?
c. How many leaves are in the tree?
d. What is the height of the tree?
e. What is the height of the left subtree?
f. What is the height of the right subtree?
g. What is the level of F?
h. What is the depth of C?
i. How many children does C have?
j. What is the parent of F?
k. What are the descendants of B?
l. What are the ancestors of F?
m. What would the output be if the elements were written out during an inOrder traversal?
n. What would the output be if the elements were written out during a postOrder traversal?
o. What would the output be if the elements were written out during a preOrder traversal?
p. What would the output be if the elements were written out during a breadth-first traversal? Get the solution of 9.1


9.2 a. Construct a binary tree of height 3 that has 8 elements.
b. Can you construct a binary tree of height 2 that has 8 elements?
c. For n going from 1 to 20, determine the minimum height possible for a binary tree with n elements.
d. Based on your calculations in part c, try to develop a formula for the minimum height possible for a binary tree with n elements, where n can be any positive integer.
e. Use the Principle of Mathematical Induction (Strong Form) to prove the correctness of your formula in part d. Get the solution of 9.2


9.3 a. What is the maximum number of leaves possible in a binary tree with 10 elements? Construct such a tree.
b. What is the minimum number of leaves possible in a binary tree with 10 elements? Construct such
a tree. Get the solution of 9.3


9.4 a. Construct a two-tree that is not complete.
b. Construct a complete tree that is not a two-tree.
c. Construct a complete two-tree that is not full.
d. How many leaves are there in a two-tree with 17 elements?
e. How many leaves are there in a two-tree with 731 elements?
f. A non-empty two-tree must always have an odd number of elements. Why?
Hint: Use the Binary Tree Theorem and the fact that the number of leaves must be an integer.
g. How many elements are there in a full binary tree of height 4?
h. How many elements are there in a full binary tree of height 12?
i. Use induction (original form) on the height of the tree to show that any full binary tree is a two tree.
j. Use the results from part i and the Binary Tree Theorem to determine the number of leaves in a full binary tree with 63 elements.
k. Construct a complete two-tree that is not full, but in which the heights of the left and right subtrees are equal.  Get the solution of 9.4


9.5 For the following binary tree, show the order in which elements would be visited for an inOrder, postOrder, preOrder, and breadthFirst traversal.

9.6 Show that a binary tree with n elements has 2n + 1 subtrees (including the entire tree). How many of these subtrees are empty? Get the solution of 9.6


9.7 Show that if t is a complete binary tree, then
height(t ) = floor(log2(n(t )))
Hint: Let t be a complete binary tree of height k ≥ 0, and let t1 be a full binary tree of height k − 1. Then n(t1) + 1 ≤ n(t ). Use Part 4 of the Binary Tree Theorem to show that floor(log2 (n(t1) + 1)) = k, and use Part 1 of the Binary Tree Theorem to show that floor(log2(n(t ))) < k + 1. Get the solution of 9.7


9.8 The Binary Tree Theorem is stated for non-empty binary trees. Show that parts 1, 2, and 4 hold even for an empty binary tree. Get the solution of 9.8


9.9 Give an example of a non-empty binary tree that is not a two-tree but
leaves(t) = (n(t) + 1) / 2
Hint: The denominator is 2, not 2.0, so integer division is performed. Get the solution of 9.9


9.10 Let t be a non-empty tree. Show that if
leaves(t ) = n(t ) + 1 / 2.0
then either both subtrees of t are empty or both subtrees of t are non-empty.
Note: Do not use Part 3 of the Binary Tree Theorem. This exercise can be used in the proof of Part 3. Get the solution of 9.10


9.11 Show that in any complete binary tree t, at least half of the elements are leaves.
Hint: if t is empty, there are no elements, so the claim is vacuously true. If the leaf at the highest index is a right child, then t is a two-tree, and the claim follows from part 3 of the Binary Tree Theorem. Otherwise, t was formed by adding a left child to the complete two-tree with n(t ) − 1 elements. Get the solution of 9.11


9.12 Compare the inOrder traversal algorithm in Section 9.5 with the move method from the Towers of Hanoi application in Section 5.4 of Chapter 5. They have the same structure, but worstTime(n) is linear in n for the inOrder algorithm and exponential in n for the move method. Explain. Get the solution of 9.12

9.13 Let t be a nonempty binary tree. Use the Strong Form of the Principle of Mathematical Induction to prove each of the following parts of the Binary Tree Theorem:
a.
n(t ) + 1
2.0 ≤ 2height(t )
b. If t is a two-tree, then leaves(t ) = n(t ) + 1 / 2.0
c. If t is a full tree, then
n(t ) + 1 /  2.0 = 2height(t )
Hint: The outline of the proof is the same as in Example A2.5 of Appendix 2. Get the solution of 9.13


9.14 Let t be a nonempty binary tree. Use the Strong Form of the Principle of Mathematical Induction to prove each of the following parts of the Binary Tree Theorem:
a. If leaves(t ) = n(t ) + 1  / 2.0
then t is a two-tree.
b. If
n(t ) + 1
2.0 = 2height(t ) then t is a full tree.
Hint: The proof for both parts has the same outline. For example, here is the outline for part a:
For h = 0, 1, 2, . . . , let Sh be the statement
If t is a binary tree of height h and leaves(t ) = n(t ) + 1  / 2.0
then t is a two-tree.
In the inductive case, let h be any nonnegative integer and assume that S0, S1, . . ., Sh are all true. To show that Sh+1 is true, let t be a binary tree of height h + 1 such that
leaves(t ) = n(t ) + 1 / 2.0
First, show that
leaves(leftTree(t )) + leaves(rightTree(t )) = n(leftTree(t )) + 1 / 2.0 +  n(rightTree(t )) + 1 / 2.0
For any non-negative integers a, b, c, and d, if
a + b = c + d and a ≤ c and b ≥ d, then a = c and b = d.
Then, using Exercise 8.10, show that leftTree(t) and rightTree(t) are two-trees. Then, using Exercise
8.8, show that both leftTree(t) and rightTree(t) are nonempty. Conclude, from the definition of a two-tree, that t must be a two-tree. Get the solution of 9.14


9.15 For any positive integer n, we can construct a binary tree of n elements as follows:
at level 0, there will be 1 element (the root);
at level 1, there will be 2 elements;
at level 2, there will be 3 elements;
at level 3, there will be 4 elements;
at level 4, there will be 5 elements;
. . .
At the level farthest from the root, there will be just enough elements so the entire tree will have n elements.
For example, if n = 12, we can construct the following tree:







Provide a ! estimate of the height as a function of n.
Hint: Since ! is just an estimate, we can ignore the elements at the lowest level. We seek an integer h such that
1 + 2 + 3 + 4 + . . . + (h + 1) = n
See Example A2.1 in Appendix 2.
Note: This exercise is contrived but, in fact, the ! estimate of the average height of a binary tree is the same as the answer to this exercise (see Flajolet, [1981]).  Get the solution of 9.15

Data Structures and Java Collection Framework - William Collins - Chapter 8 Solutions

CONCEPT EXERCISES
8.1 What advantage was obtained by implementing the List interface before declaring the Stack class? Get the solution of 8.1


8.2 Suppose we define:
Queue<Integer> queue = new LinkedList<Integer>();
Show what the LinkedList object (referenced by) queue will look like after each of the following messages is sent:
a. queue.add (2000);
b. queue. add (1215);
c. queue. add (1035);
d. queue. add (2117);
e. queue.remove();
f. queue. add (1999);
g. queue.remove(); Get the solution of 8.2


8.3 Re-do Exercise 8.2, parts a through g, for a stack instead of a queue. Start with
Stack<Integer> stack = new Stack<Integer>();
stack.push (2000); Get the solution of 8.3


8.4 Suppose that elements "a", "b", "c", "d", "e" are pushed, in that order, onto an initially empty stack, which is then popped four times, and as each element is popped, it is enqueued into an initially empty queue.
If one element is then dequeued from the queue, what is the next element to be dequeued? Get the solution of 8.4


8.5 Use a stack of activation records to trace the execution of the recursive fact method after an initial call of fact (4). Here is the method definition:
/**
/**
* Calculates n!.
*
* @param n the integer whose factorial is calculated.
*
* @return n!.
*
*/
protected static long fact (int n)
{
if (n <= 1)
return 1;
return n ∗ fact (n - 1);
} // method fact Get the solution of 8.5

8.6 Translate the following expressions into postfix notation:
1. x + y ∗ z
2. (x + y) ∗ z
3. x − y − z ∗ (a + b)
4. (a + b) ∗ c − (d + e ∗ f/((g/h + i − j) ∗ k))/ r
Test your answers by running the InfixToPostfix project in Lab 15.  Get the solution of 8.6


8.7 Translate each of the expressions in Programming Exercise 8.6 into prefix notation. Get the solution of 8.7


8.8 An expression in postfix notation can be evaluated at run time by means of a stack. For simplicity, assume that the postfix expression consists of integer values and binary operators only. For example, we might have the following postfix expression:
8 5 4 + ∗ 7 −
The evaluation proceeds as follows: When a value is encountered, it is pushed onto the stack. When an operator is encountered, the first—that is, top—and second elements on the stack are retrieved and popped, the operator is applied (the second element is the left operand, the first element is the right operand) and the result is pushed onto the stack. When the postfix expression has been processed, the value of that expression is the top (and only) element on the stack.
For example, for the preceding expression, the contents of the stack would be as follows:
4
5 5
8 8 8
----- ----- ----- -----
9 7
8 72 72 65
----- ----- ----- -----
Convert the following expression into postfix notation and then use a stack to evaluate the expression:
5 + 2 ∗ (30 − 10/5)  Get the solution of 8.8

PROGRAMMING EXERCISES
8.1 Declare and test the PureStack class (see Section 8.1.2) with a LinkedList field.
Hint: Each of the definitions is a one-liner. Get the solution of 8.1


8.2 Declare and test the PureStack class (see Section 8.1.2) with an ArrayList field.
Hint: For the sake of efficiency, the top of the stack should be at index size() - 1. Get the solution of 8.2


8.3 Develop an iterative, stack-based version of the ways method in Programming Exercise 5.7. Test your method with unit testing. Get the solution of 8.3

Data Structures and Java Collection Framework - William Collins - Chapter 7 Solutions

7.1 In the SinglyLinkedList class, define the following method without using an iterator.
/**
* Finds the element at a specified position in this LinkedList object.
* The worstTime(n) is O(n).
*
* @param index – the position of the element to be returned.
*
* @return the element at position index.
*
* @throws IndexOutOfBoundsException – if index is less than 0 or greater than
* or equal to size().
*/
public E get (int index) Get the solution of 7.1


7.2 Re-do Concept Exercise 7.1 by using an iterator. Get the solution of 7.2


7.3 Suppose we added each of the following methods to the ArrayList class:
public boolean addFirst (E element);
public boolean addLast (E element);
public E getFirst();
public E getLast();
public E removeFirst();
public E removeLast();
Estimate worstTime(n) for each method. Get the solution of 7.3


7.4 The listIterator() method can be called by a LinkedList object, but is not defined within the
LinkedList class. In what class is that listIterator() method defined? What is that definition? Get the solution of 7.4


7.5 One of the possibilities for fields in the LinkedList class was to have head and tail fields, both of type Entry, where the Entry class had element and next fields, but no previous field. Then we would have a singly-linked list.
a. Define the addLast method for this design. Here is the method specification:
/**
* Appends a specified element to (the back of) this LinkedList object.
*
* @param element – the element to be appended.
*
* @return true.
*
*/
public boolean addLast (E element)
b. The definition of the removeLast() method would need to make null the next field in the Entry
object before the Entry object tail. Could we avoid a loop in the definition of removeLast() if, in the
LinkedList class, we added a beforeTail field that pointed to the Entry object before the Entry
object tail ? Explain. Get the solution of 7.5

7.6 How can you distinguish between a call to the add (E element) method in the LinkedList class and a call to the add (E element) method in the ListItr class? Get the solution of 7.6


7.7 Explain how to remove “Don” from the LinkedList object in Figure 7.18. Explain why, for the definition of the method remove (Object obj), worstTime(n) is linear in n? Get the solution of 7.7


7.8 In the Java Collections Framework, the LinkedList class is designed as a circular, doubly-linked list with a dummy entry (pointed to by the header field). What is the main advantage of this approach over a circular, doubly-linked list with head and tail fields? Get the solution of 7.8


PROGRAMMING EXERCISES
7.1 Use the SinglyLinkedList class three times. First, create a SinglyLinkedList object, team1,
with elements of type String. Add three elements to team1. Second, create team2, another
SinglyLinkedList object with elements of type String. Add four elements to team2. Finally, create
a SinglyLinkedList object, league, whose elements are SinglyLinkedList objects of teams.
Add team1 and team2 to league. Get the solution of 7.1


7.2 Hypothesize the output from the following method segment:
LinkedList<Character> letters = new LinkedList<Character>();
ListIterator<Character> itr = letters.listIterator();
itr.add (‘f’);
itr.add (‘t’);
itr.previous();
itr.previous();
itr.add (‘e’);
itr.add (‘r’);
itr.next();
itr.add (‘e’);
itr.add (‘c’);
itr = letters.listIterator();
itr.add (‘p’);
System.out.println (letters);
Test your hypothesis.  Get the solution of 7.2


7.3 Rewrite the code in Programming Exercise 7.2 without using an iterator. For example, you would
start with:
LinkedList<Character> letters = new LinkedList<Character>();
letters.add (0, ‘f’);
Test your revision. Get the solution of 7.3

7.4 Rewrite the code in Exercise 7.2 with a native array. For example, you would start with:
char [ ] letters = new char [10];
letters [0] = ‘f’;
Test your revision. Get the solution of 7.4


7.5 Hypothesize the error in the following code:
LinkedList<Double> duesList = new LinkedList<Double>();
ListItr<Double> itr = duesList.listIterator();
Test your hypothesis. Get the solution of 7.5


7.6 Suppose we have the following:
LinkedList<Double> weights = new LinkedList<Double>();
ListIterator<Double> itr;
weights.add (5.3);
weights.add (2.8);
itr = weights.listIterator();
Hypothesize which of the following sequences of messages would now be legal:
a. itr.add (8.8); itr.next(); itr.remove();
b. itr.add (8.8); itr.remove(); itr.next();
c. itr.next(); itr.add (8.8); itr.remove();
d. itr.next(); itr.remove(); itr.add (8.8);
e. itr.remove(); itr.add (8.8); itr.next();
f. itr.remove(); itr.next(); itr.add (8.8);
Test your hypotheses. Get the solution of 7.6


7.7 Suppose you decided to rewrite the VeryLongInt class, from Chapter 6, with a LinkedList instead
of an ArrayList. The main change is to replace each occurrence of the identifier ArrayList with
LinkedList. Another change, in the String -parameter constructor, is to replace
digits = new ArrayList<Integer> (s.length());
with digits = new LinkedList<Integer>();
But the add method will now take quadratic time because the least method will now take linear time.
Modify the least method—including its heading—so that its worstTime(n) will be constant. Make the
corresponding changes to the add method so that method will take only linear time. Get the solution of 7.7

7.8 Rewrite the insert method in the Editor class to insert the given line after the current line. For example, if the text is
>I was
older then
and the command is
$Insert
so much
then the text becomes
I was
>so much
older then
The newly added line becomes the current line. Get the solution of 7.8


7.9 Modify the EditorUser class to work with commands entered from the keyboard instead of a file. The output should go to the console window. Test your changes by entering, from the keyboard, the lines in editor.in1 from the Editor directory on the book’s website. Get the solution of 7.9


7.10 Unit test and define the following method:
/**
* Removes the first and last 4-letter word from a given LinkedList<String> object.
* Each word will consist of letters only.
* The worstTime(n) is O(n).
*
* @param list – the LinkedList<String> object.
*
* @throws NullPointerException – if list is null.
* @throws NoSuchElementException - if list is not null, but list has no 4-letter
* words or only one 4-letter word.
*
*/
public static void bleep (LinkedList<String> list) Get the solution of 7.10

Data Structures and Java Collection Framework - William Collins - Chapter 6 Solutions

CONCEPT EXERCISES
6.1 State two advantages, and one disadvantage, of using an ArrayList object instead of an array object. Get the solution of 6.1


6.2 Show that, for the task of appending n elements to an ArrayList object, worstTime(n) is linear in n. Get the solution of 6.2


6.3 The one-parameter add method in the ArrayList class always returns true. Would it make sense to change the return type from boolean to void ? Explain. Get the solution of 6.3


6.4 For the one-parameter add method in the ArrayList class, estimate worstSpace(n) and averageSpace(n). Get the solution of 6.4


6.5 In choosing fields for the VeryLongInt class, we decided to use, rather than inherit from, the ArrayList class. Why?
Hint: How much commonality is there between the methods in the ArrayList class and the methods in the VeryLongInt class? Get the solution of 6.5


6.6 Suppose you modified the VeryLongInt class as follows: each element in digits consists of a five-digit integer. What effect do you think this will have on Big-O time? What about run-time? Get the solution of 6.6


6.7 Suppose, in developing the VeryLongInt class, we decide that digits will contain the integer in reverse order. For example, if the constructor call is:
VeryLongInt veryLong = new VeryLongInt ("386");
we would have (Integer elements with values) 6, 8, 3 in positions 0 through 2, respectively of digits.
Re-design this constructor so that worstTime(n) is still linear in n. Get the solution of 6.7


6.8 Which parts of the VeryLongInt methods would have to be re-written if digits were an array object of int elements instead of an ArrayList object of Integer elements? Get the solution of 6.8


6.9 How can a user of the VeryLongInt class easily create a VeryLongInt object that is a copy of an already existing VeryLongInt object? Get the solution of 6.9

PROGRAMMING EXERCISES
6.1 Hypothesize the output from the following code, and then test your hypothesis with a small program that includes the code:
ArrayList<String> letters = new ArrayList<String>();
letters.add ("f");
letters.add (1, "i");
letters.add ("e");
letters.add (1, "r");
letters.add ("e");
letters.add (4, "z");
System.out.println (letters);
letters.remove ("i");
int index = letters.indexOf ("e");
letters.remove (index);
letters.add (2, "o");
System.out.println (letters); Get the solution of 6.1

6.2 For each of the following program segments, hypothesize if the segment would generate a compile-time error, a run-time exception, or neither. Then test your hypotheses with a main method that includes each segment.
a. ArrayList<String> myList = new ArrayList<String>();
myList.add ("yes");
myList.add (7);
b. ArrayList<Double> original = new ArrayList<Double>();
original.add (7);
c. ArrayList<Integer> original = new ArrayList<Integer>();
double x = 7;
original.add (x);
d. ArrayList<String> newList = new ArrayList<String>();
newList.add ("yes");
Integer answer = (Integer)newList.get (0); Get the solution of 6.2


6.3 Suppose we have the following code:
ArrayList<String> myList = new ArrayList<String>();
myList.add ("Karen");
myList.add ("Don");
myList.add ("Mark");
ArrayList<String> temp = new ArrayList<String> (myList);
ArrayList<String> sameList = myList;
myList.add (1, "Courtney");
Hypothesize what the contents of myList, temp, and sameList will be after this last insertion. Then test your hypothesis with a main method that includes the code. Get the solution of 6.3


6.4 Hypothesize what will happen when the following code fragment is run, and then test your hypothesis:
ArrayList<String> original = new ArrayList<String>();
original.add ("yes");
ArrayList<Integer> copy = (ArrayList<Integer>)original.clone();
System.out.println (copy.get (0));
Hint: This exercise illustrates why the copy constructor is superior to the clone() method. Get the solution of 6.4


6.5 Expand the VeryLongInt class by testing and defining methods that have the following method specifications:
a. /**
* Initializes this VeryLongInt object from a given int.
*
* @param n – the int from which this VeryLongInt is initialized.
*
* @throws IllegalArgumentException – if n is negative.
*
*/
public VeryLongInt (int n)

b. /**
* Returns the number of digits in this VeryLongInt object.
*
* @return the number of digits in this VeryLongInt object.
*
*/
public int size()
c. /**
* Returns true if this VeryLongInt object is less than another VeryLongInt
* object. The worstTime(n) is O(n).
*
* @param otherVeryLong – the other VeryLongInt object.
*
* @return true – if this VeryLongInt is less than otherVeryLong.
*
* @throws NullPointerException – if otherVeryLong is null
*
*/
public boolean less (VeryLongInt otherVeryLong)
d. /**
* Returns true if this VeryLongInt object is greater than another VeryLongInt
* object. The worstTime(n) is O(n).
*
* @param otherVeryLong – the other VeryLongInt object.
*
* @return true – if this VeryLongInt is greater than otherVeryLong.
*
* @throws NullPointerException – if otherVeryLong is null
*
*/
public boolean greater (VeryLongInt otherVeryLong)
e. /**
* Returns true if this VeryLongInt object is equal to a specified object.
* The worstTime(n) is O(n).
*
* @param obj – the specified object that this VeryLongInt is compared to.
*
* @return true – if this VeryLongInt is equal to obj.
*
*/
public boolean equals (Object obj)
f. /**
* Stores a Fibonacci number in this VeryLongInt object.
*
* @param n – the index in the Fibonacci sequence
*
* @throws IllegalArgumentException – if n is not positive

*/
public void fibonacci (int n)
Example Suppose the following message is sent
tempInt.fibonacci (100);
Then tempInt’s value will be 354224848179261915075—the 100th Fibonacci number.
Hint: Mimic the iterative design of the Fibonacci function from Lab 7. Both i and n will be ordinary int variables, but previous, current and temp will be VeryLongInt objects. After the loop, instead of
returning current, the calling object is modified by assigning to digits a copy of current.digits. Get the solution of 6.5


6.6 Assume that myList is (a reference to) an ArrayList<Double> object and that both i and j are int
variables with values in the range from 0 to myList.size() -1, inclusive. Hypothesize what the following accomplishes, and then test your hypothesis.
myList.set (i, myList.set (j, myList.get (i))); Get the solution of 6.6


6.7 Describe how to find the method definitions for the ArrayList class in your computing environment. Get the solution of 6.7


6.8 Modify the simple program in Section 6.2.2 so that all removals are performed in a single loop.
Hint: Create a temporary ArrayList object to hold the un-removed elements. What is a drawback to
 this approach? Get the solution of 6.8


6.9 Convert the simple program in Section 6.2.2 into one that uses an array object instead of an ArrayList object. Get the solution of 6.9


6.10 Modify the simple program in Section 6.2.2 to use a binary search instead of the sequential search used in the call to the indexOf method. The Collections class in java.util has a binarySearch method and a sort method. Get the solution of 6.10


6.11 Suppose scoreList is an ArrayList object of Integer elements, and the following message is sent:
scoreList.remove (3);
Does this message remove the element at index 3, or remove the first occurrence of new Integer (3)?
Test your hypothesis. Get the solution of 6.11


6.12 Suppose we create the following ArrayList instance:
ArrayList<String> words = new ArrayList<String>();
And then we insert several words into words. Write the code to print out each element of words that has exactly four letters. You should have three different versions of the code:
a. using an index;
b. using an explicit iterator;
c. using an enhanced for statement. Get the solution of 6.12


6.13 Test and define the following method
/**
* In a given ArrayList, remove all duplicates.
* The worstTime(n) is O(n2 ).
*
* @param list - the given ArrayList.
*

* @return – An ArrayList that is identical to list except only the first
* occurrence of duplicate elements remains.
*
* @throws NullPointerException - if list is null.
*
*/
public static <T> ArrayList <T> uniquefy (ArrayList <T> list)
For example, suppose myList consists of references to Integer objects with the following values, in
sequence 3, 8, 6, 4, 8, 7, 8, 9, 4
Then the ArrayList returned by the call to uniquefy (myList) will consist of references to Integer
objects with the following values, in sequence
3, 8, 6, 4, 7, 9  Get the solution of 6.13

Data Structures and Java Collection Framework - William Collins - Chapter 5 Solutions

CONCEPT EXERCISES
5.1 What is wrong with the following underlying method for calculating factorials?
/**
* Calculates the factorial of a non-negative integer, that is, the product of all
* integers between 1 and the given integer, inclusive. The worstTime(n) is O(n),
* where n is the given integer.
*
* @param n the non-negative integer whose factorial is calculated.
*
* @return the factorial of n
*
*/
public static long fact (int n)
{
if (n <= 1)
return 1;
return fact (n+1) / (n+1);
} // fact  Get the solution of 5.1


5.2 Show the first three steps in an execution-frames trace of the move method after an initial call of
move (4, 'A', 'B', 'C'); Get the solution of 5.2


5.3 Perform an execution-frames trace to determine the output from the following incorrect version of the recPermute method (from Lab 9) after an initial call to permute ("ABC");
invokes recPermute ([‘A’, ‘B’, ‘C’], 0);
/**
* Finds all permutations of a subarray from a given position to the end of the array.
*
* @param c an array of characters
* @param k the starting position in c of the subarray to be permuted.
*
* @return a String representation of all the permutations.
*
*/
public static String recPermute (char[ ] c, int k)
{
if (k == c.length - 1)
return String.valueOf (c) + "\n";
else
{
String allPermutations = new String();
char temp;

for (int i = k; i < c.length; i++)
{
temp = c [i];
c [i] = c [k + 1];
c [k + 1] = temp;
allPermutations += recPermute (String.valueOf (c).toCharArray(), k+1);
} // for
return allPermutations;
} // else
} // method recPermute  Get the solution of 5.3


5.4 Perform an execution-frames trace to determine the output from the following incorrect version of the recPermute method (from Lab 9) after an initial call to permute ("ABC");
invokes recPermute ([‘A’, ‘B’, ‘C’], 0);
/**
* Finds all permutations of a subarray from a given position to the end of the array.
*
* @param c an array of characters
* @param k the starting position in c of the subarray to be permuted.
*
* @return a String representation of all the permutations.
*
*/
public static String recPermute (char[ ] c, int k)
{
if (k == c.length - 1)
return String.valueOf (c) + "\n";
else
{
String allPermutations = new String();
char temp;
for (int i = k; i < c.length; i++)
{
allPermutations += recPermute (String.valueOf (c).toCharArray(), k+1);
temp = c [i];
c [i] = c [k];
c [k] = temp;
} // for
return allPermutations;
} // else
} // method recPermute   Get the solution of 5.4


5.5 Use the Principle of Mathematical Induction (Appendix 1) to prove that the move method in the Towers of Hanoi example is correct, that is, for any integern > = 1, move (n, orig, dest, temp) returns the steps to move n disks from pole orig to pole dest.
Hint: for n = 1, 2, 3, . . . , let Sn be the statement: move (n, orig, dest, temp) returns the steps to move n disks from any pole orig to any other pole dest.
a. base case. Show that S1 is true.
b. inductive case. Let n be any integer greater than 1 and assume Sn−1 is true. Then show that Sn is true.
According the code of the move method, what happens when move (n, orig, dest, temp) is
called and n is greater than 1? Get the solution of 5.5


5.6 In an execution trace of the move method in the Towers of Hanoi application, the number of steps is equal to the number of recursive calls to the move method plus the number of direct moves. Because each call to the move method includes a direct move, the number of recursive calls to the move method is always one less than the number of direct moves. For example, in the execution trace shown in the chapter, n = 3. The total number of calls to move is 2n − 1 = 7. Then the number of recursive calls to move is 6, and the number of direct moves is 7, for a total of 13 steps (recall that we started at Step 0, so the last step is Step 12). How many steps would there be for an execution trace with n = 4?  Get the solution of 5.6

5.7 Show that, for the recursive binarySearch method, averageTime(n) is logarithmic in n for a successful search.
Hint: Let n represent the size of the array to be searched. Because the average number of calls is a nondecreasing function of n, it is enough to show that the claim is true for values of n that are one less than a power of 2. So assume that n = 2k − 1, for some positive integer k.
In a successful search, one call is sufficient if the item sought is half-way through the region to be searched; two calls are needed if the item sought is one-fourth or three-fourths of the way through that region; three calls are needed if the item sought is one-eighth, three-eighths, five-eighths or seven-eighths of the way through the region;
and so on.
The total number of calls for all successful searches is
(1 ∗ 1) + (2 ∗ 2) + (3 ∗ 4) + (4 ∗ 8) + (5 ∗ 16) + ·· ·+(k ∗ 2k−1)
The average number of calls, and hence an estimate of averageTime(n), is this sum divided by n. Now use the result from Exercise 2.6 of Appendix 2 and the fact that
k = log2 (n + 1) Get the solution of 5.7


5.8 If a call to the binarySearch method is successful, will the index returned always be the smallest index of an item equal to the key sought? Explain. Get the solution of 5.8


PROGRAMMING EXERCISES
5.1 Develop an iterative version of the getBinary method in Section 5.3. Test that method with the same BinaryTest class (available on the book’s website) used to test the recursive version. Get the solution of 5.1

5.2 Develop an iterative version of the permute method (from Lab 9). Here is the method specification:
/**
* Finds all permutations of a specified String.
*
* @param s - the String to be permuted.
*
* @return a String representation of all the permutations, with a line separator
* (that is, "\n") after each permutation.
*/
public static String permute (String s)
For example, if the original string is “BADCGEFH”, the value returned would be
ABCDEFGH
ABCDEFHG
ABCDEGFH
ABCDEGHF
ABCDEHFG
and so on. Test your method with the same PermuteTest method developed in Lab 9 to test the recursive version.
Hint: One strategy starts by converting s to a character array c. Then the elements in c can be easily
swapped with the help of the index operator, [ ]. To get the first permutation, use the static method sort in the Arrays class of java.util. To give you an idea of how the next permutation can be constructed from the current permutation, suppose, after some permutations have been printed,
c = ['A', 'H', 'E', 'G', 'F', 'D', 'C', 'B']
What is the smallest index whose character will be swapped to obtain the next permutation? It is index 2, because the characters at indexes 3 through 7 are already in reverse alphabetical order: ‘G’ > ‘F’ > ‘D’ > ‘C’ > ‘B’. We swap ‘E’ with ‘F’, the smallest character greater than ‘E’ at an index greater than 2. After swapping, we have c = ['A', 'H', 'F', 'G', 'E', 'D', 'C', 'B']
We then reverse the characters at indexes 3 through 7 to get those characters into increasing order:
c = ['A', 'H', 'F', 'B', 'C', 'D', 'E', 'G'], the next higher permutation after ‘A’, ‘H’, ‘E’, ‘G’, ‘F’, ‘D’, ‘C’, ‘B’.
Here is an outline:
public static String permute (String s)
{
int n = s.length();
boolean finished = false;
char[ ] c = s.toCharArray();
String perms = "";
Arrays.sort (c); // c is now in ascending order
while (!finished)
{
perms += String.valueOf (c));
// In 0 ... n-1, find the highest index p such that
// p = 0 or c [p - 1] < c [p].
...
if (p == 0)
finished = true;
else
{
// In p ... n-1, find the largest index i such that c [i] > c [p - 1].
...
// Swap c [i] with c [p - 1].
// Swap c [p] with c [n-1], swap c [p+1] with c[n-2],
// swap c [p+2] with c [n-3], ...
...
} // else
} // while
return perms;
} // method permute
In the above example, p - 1 = 2 and i = 4, so c [p - 1], namely, ‘E’ is swapped with c [i],
namely, ‘F’.
Explain how strings with duplicate characters are treated differently in this method than in the recursive version.  Get the solution of 5.2


5.3 Given two positive integers i and j, the greatest common divisor of i and j, written
gcd (i, j) is the largest integer k such that (i % k = 0) and (j % k = 0).
For example, gcd (35, 21) = 7 and gcd (8, 15) = 1. Test and develop a wrapper method and a wrapped
recursive method that return the greatest common divisor of i and j. Here is the method specification for the wrapper method:
/**
* Finds the greatest common divisor of two given positive integers
*
* @param i – one of the given positive integers.
* @param j – the other given positive integer.
* @return the greatest common divisor of iand j.
*
* @throws IllegalArgumentException – if either i or j is not a positive integer.
*
*/
public static int gcd (int i, int j)
Big hint: According to Euclid’s algorithm, the greatest common divisor of i and j is j if i % j = 0. Otherwise,
the greatest common divisor of i and j is the greatest common divisor of j and (i % j).  Get the solution of 5.3


5.4 A palindrome is a string that is the same from right-to-left as from left-to-right. For example, the following
are palindromes:
ABADABA
RADAR
OTTO
MADAMIMADAM
EVE
For this exercise, we restrict each string to upper-case letters only. (You are asked to remove this restriction in the next exercise.)
Test and develop a method that uses recursion to check for palindromes. The only parameter is a string that is to be checked for palindromity. The method specification is
/**
* Determines whether a given string of upper-case letters is a palindrome.
* A palindrome is a string that is the same from right-to-left as from left-to-right.
*
* @param s – (a reference to) the given string
*
* @return true – if the string s is a palindrome; otherwise, false.
*
* @throws NullPointerException – if s is null.
* @throws IllegalArgumentException – if s is the empty string.
*
*/
public static boolean isPalindrome (String s)  Get the solution of 5.4


5.5 Expand the recursive method (and test class) developed in Programming Exercise 5.4 so that, in testing to see whether s is a palindrome, non-letters are ignored and no distinction is made between upper-case and lower-case letters. Throw IllegalArgumentException if s has no letters. For example, the following are palindromes:
Madam, I’m Adam.
Able was I ’ere I saw Elba.
A man. A plan. A canal. Panama!
Hint: The toUpperCase() method in the String class returns the upper-case String corresponding to
the calling object.  Get the solution of 5.5

5.6 .a. Test and develop a wrapper method power and an underlying recursive method that return the result of integer exponentiation. The method specification of the wrapper method is
/**
* Calculates the value of a given integer raised to the power of a second integer.
* The worstTime(n) is O(n), where n is the second integer.
*
* @param i – the base integer (to be raised to a power).
* @param n – the exponent (the power i is to be raised to).
*
* @return the value of i to the nth power.
*
* @throws IllegalArgumentException – if n is a negative integer or if i raised to
* to the n is greater than Long.MAX_VALUE.
*
*/
public static long power (long i, int n)
Hint: We define 00 = 1, so for any integer i , i 0 = 1. For any integers i> 0 and n > 0,
i n = i∗i n−1
b. Develop an iterative version of the power method.
c. Develop an underlying recursive version called by the power method for which worstTime(n) is logarithmic in n.
Hint: If n is even, power (i, n) = power (i * i, n/2); if n is odd, power (i, n) = i *
in - 1 = i * power (i * i, n/2).
For testing parts b and c, use the same test suite you developed for part a.  Get the solution of 5.6


5.7 Test and develop a recursive method to determine the number of distinct ways in which a given amount of money in cents can be changed into quarters, dimes, nickels, and pennies. For example, if the amount is 17 cents, then there are six ways to make change:
1 dime, 1 nickel and 2 pennies;
1 dime and 7 pennies;
3 nickels and 2 pennies;
2 nickels and 7 pennies;
1 nickel and 12 pennies;
17 pennies.

Here are some amount/ways pairs. The first number in each pair is the amount, and the second number is the number of ways in which that amount can be changed into quarters, dimes, nickels and pennies:
17 6
5 2
10 4
25 13
42 31
61 73
99 213

/**
* Calculates the number of ways that a given amount can be changed
* into coins whose values are no larger than a given denomination.
*
* @param amount – the given amount.
* @param denomination – the given denomination (1 = penny,
* 2= nickel, 3 = dime, 4 = quarter).
*
* @return 0 – if amount is less than 0; otherwise, the number of ways
* that amount can be changed into coins whose values are no
* larger than denomination.
*
*/
public static int ways (int amount, int denomination)
For the sake of simplifying the ways method, either develop an enumerated type Coin or develop a coins method that returns the value of each denomination. Thus, coins (1) returns 1, coins (2) returns 5, coins (3) returns 10, and coins (4) returns 25.
Hint: The number of ways that one can make change for an amount using coins no larger than a quarter is equal to the number of ways that one can make change for amount—25 using coins no larger than a quarter plus the number of ways one can make change for amount using coins no larger than a dime.  Get the solution of 5.7


5.8 Modify the maze-search application to allow an end user to enter the maze information directly, instead of in a file. Throw exceptions for incorrect row or column numbers in the start and finish positions. Get the solution of 5.8


5.9 Modify the maze-search application so that diagonal moves would be valid.
Hint: only the MazeIterator class needs to be modified. Get the solution of 5.9


Data Structures and Java Collection Framework - William Collins - Chapter 1 Solutions

CONCEPT EXERCISES
1.1 Given that HourlyEmployee and SalariedEmployee are subclasses of FullTimeEmployee, suppose
we have:
FullTimeEmployee full = new FullTimeEmployee();
HourlyEmployee hourly = new HourlyEmployee ();
SalariedEmployee salaried = new SalariedEmployee ();
full = salaried;
Which one of the following assignments would be legal both at compile-time and at run-time?
a. salaried = (SalariedEmployee) full;
b. salaried = full;
c. salaried = (FullTimeEmployee) full;
d. hourly = (HourlyEmployee) full;
Create a small project to validate your claim. Get the solution of 1.1


1.2 Assume that the classes below are all in the file Polymorphism.java. Determine the output when
the project is run. Would the output be different if the call to println were System.out.println
(a.toString())?
import java.util.*;
public class Polymorphism
{
public static void main (String args [ ])
{
new Polymorphism().run();
} // method main
public void run()
{
Scanner sc = new Scanner (System.in));
A a;
int code = sc.nextInt();
if (code == 0)
a = new A();
else // non-zero int entered
a = new D();
System.out.println (a);
} // method run
} // class Polymorphism

class A
{
public String toString ()
{
return "A";
} // method toString
} // class A
class D extends A
{
public String toString ()
{
return "D";
} // method toString
} // class D  Get the solution of 1.2


1.3 In the Employee class, modify the toString method so that the gross pay is printed with a comma to the
left of the hundreds digit. For example, if the name is “O’Brien,Theresa” and the gross pay is 74400.00, the
toString method will return
O’Brien,Theresa $74,400.00 Get the solution of 1.3


1.4 What can you infer about the identifier out from the following message?
System.out.println ("Eureka!");
What is the complete declaration for the identifier out? Look in java.lang.System.java. Get the solution of 1.4


PROGRAMMING EXERCISES

1.1 Here is a simple class—but with method specifications instead of method definitions—to find the highest age from the ages scanned in:
public class Age
{
protected int highestAge;
/**
* Initializes this Age object.
*
*/
public Age ()
/**
* Returns the highest age of the ages scanned in from the keyboard.

* The sentinel is -1.
*
* @param sc – The Scanner used to scan in the ages.
*
* @return the highest age of the ages scanned in from sc.
*
*/
public int findHighestAge (Scanner sc)
} // class Age
a. Fill in the method definitions for the Age class.
b. Test your Age class by developing a project and running the project. Get the solution of 1.1


1.2 With the Age class in Programming Exercise 1.1.a. as a guide, develop a Salary class to scan in salaries from the input until the sentinel (−1.00) is reached, and to print out the average of those salaries. The average salary is the total of the salaries divided by the number of salaries. Get the solution of 1.2


1.3 This exercise presents an alternative to having protected fields. Modify the FullTimeEmployee class as follows: Change the visibility of the name and grossPay fields from protected to private, and develop public methods to get and set the values of those fields. A method that alters a field in an object is called a mutator, and a method that returns a copy of a field is called an accessor.
Here are the method specifications corresponding to the name field:
/**
* Returns this FullTimeEmployee object’s name.
*
* @return a (reference to a) copy of this FullTimeEmployee object’s
* name.
*
*/
public String getName ()
/**
* Sets this FullTimeEmployee object’s name to a specifed string.
*
* @param nameIn – the String object whose value is assigned to this
* FullTimeEmployee object’s name.
*
*/
public void setName (String nameIn) Get the solution of 1.3


1.4 Create a class to determine which hourly employee in a file received the most overtime pay. The name of the file is to be scanned in from System.in. Get the solution of 1.4


1.5 In the toString() method of the FullTimeEmployee class, there is a call to the format method. The
heading of that method is public final String format(double number)
What is the definition of that method? Get the solution of 1.5

Data Structures and Java Collection Framework - William Collins - Chapter 4 Solutions

CONCEPT EXERCISES
4.1 What is a collection? What is a collection class? What is a Collection class? Give an example of a collection that is not an instance of a collection class. Programming Project 4.1 has an example of a collection class that is not a Collection class. Get the solution of 4.1


4.2 An array is a collection, even though there is no array class. But an array of objects can be converted into an instance of the ArrayList class. Look in the file Arrays.java in the package java.util to determine the generic algorithm (that is, static method) that converts an array of objects into an ArrayList of those objects. How can that ArrayList then be printed without a loop? Get the solution of 4.2


4.3 .a. Identify each of the following as either an interface or a class:
Collection
LinkedList
Iterator
AbstractList
b. What is the difference between an interface and an abstract class?
c. Of what value is an abstract class? That is, to what extent can an abstract class make a programmer moreproductive? Get the solution of 4.3

4.4 What is a list?  Get the solution of 4.4


PROGRAMMING EXERCISES
4.1 For each of the following, create and initialize a parameterized instance, add two elements to the instance, and then print out the instance:
a. an ArrayList object, scoreList, of Integer objects;
b. a LinkedList object, salaryList, of Double objects;  Get the solution of 4.1


4.2 Develop a main method in which two ArrayList objects are created, one with String elements and one with Integer elements. For each list, add three elements to the list, remove the element at index 1, add an element at index 0, and print out the list. Get the solution of 4.2


4.3 Find an ArrayList method, other than a constructor, that is not also a method in the LinkedList class. Find a LinkedList method, other than a constructor, that is not also a method in the ArrayList class. Get the solution of 4.3


4.4 Suppose we have the following:
LinkedList<String> team = new LinkedList<String> ();
team.add ("Garcia");
Iterator<String> itr = team.iterator();
Integer player = itr.next ();
What error message will be generated? When (at compile-time or at run-time)? Test your hypotheses. Get the solution of 4.4


4.5 Use the ArrayList class three times. First, create an ArrayList object, team1, with elements of type String. Add three elements to team1. Second, create team2, another ArrayList object with elements of type String. Add four elements to team2. Finally, create an ArrayList object, league, whose elements are ArrayList objects in which each element is of type String. Add team1 and team2 to league. Get the solution of 4.5



Data Structures and Java Collection Framework - William Collins - Chapter 3 Solutions

CONCEPT EXERCISES
3.1 Create a method, sample (int n), for which worstTime(n) is O(n) but worstTime(n) is not linear in n. Hint: O(n) indicates that n may be (crudely) viewed as an upper bound, but linear-in-n indicates that n may be (crudely) viewed as both an upper bound and a lower bound. Get the solution of 3.1


3.2 Study the following algorithm:
i = 0;
while (!a [i].equals (element))
i++;
Assume that a is an array of n elements and that there is at least one index k in 0 ... n - 1 such that a
[k].equals (element).
Use Big-O notation to estimate worstTime(n). Use Big-! and Big-" notation to estimate worstTime(n). In plain English, estimate worstTime(n). Get the solution of 3.2


3.3 Study the following method:
/**
* Sorts a specified array of int values into ascending order.
* The worstTime(n) is O(n * n).
*
* @param x – the array to be sorted.
*
*/
public static void selectionSort (int [ ] x)
{
// Make x [0 ... i] sorted and <= x [i + 1] ... x [x.length -1]:
for (int i = 0; i < x.length - 1; i++)
{
int pos = i;
for (int j = i + 1; j < x.length; j++)
if (x [j] < x [pos])
pos = j;
int temp = x [i];
x [i] = x [pos];
x [pos] = temp;
} // for i
} // method selectionSort
a. For the inner for statement, when i = 0, j takes on values from 1 to n - 1, and so there are n - 1
iterations of the inner for statement when i = 0. How many iterations are there when i = 1? When
i = 2?
b. Determine, as a function of n, the total number of iterations of the inner for statement as i takes on
values from 0 to n – 2.
c. Use Big-O notation to estimate worstTime(n). In plain English, estimate worstTime(n)—the choices are constant, logarithmic in n, linear in n, linear-logarithmic in n, quadratic in n and exponential in n. Get the solution of 3.3


3.4 For each of the following functions f, where n = 0, 1, 2, 3, . . ., estimate f using Big-O notation and plain English:
Concept Exercises 129
a. f (n) = (2 + n) * (3 + log(n))
b. f (n) = 11 * log(n) + n/2 − 3452
c. f (n) = 1 + 2 + 3 +· · · + n
d. f (n) = n * (3 + n) − 7 * n
e. f (n) = 7 * n + (n − 1) * log (n − 4)
f. f (n) = log (n2)+ n
g. f (n) =
(n + 1) ∗ log(n + 1) − (n + 1) + 1
n
h. f (n) = n + n/2 + n/4 + n/8 + n/16 + ·· · Get the solution of 3.4


3.5 In the Order Hierarchy in Figure 3.1, we have . . ., O(log n), O(n1/2), . . .. Show that, for integers n >16, log2 n < n1/2. Hint from calculus: Show that for all real numbers x >16, the slope of the function log2 x is less than the slope of the function x1/2. Since log2 (16) == 161/2, we conclude that for all real numbers x >16, log2 x < x1/2. Get the solution of 3.5


3.6 For each of the following code segments, estimate worstTime(n) using Big ! notation or plain English. In each segment, S represents a sequence of statements in which there are no n-dependent loops.
a. for (int i = 0; i * i < n; i++)
S
b. for (int i = 0; Math.sqrt (i) < n; i++)
S
c. int k = 1;
for (int i = 0; i < n; i++)
k *= 2;
for (int i = 0; i < k; i++)
S
Hint: In each case, 2 is part of the answer.  Get the solution of 3.6


3.7 .a. Suppose we have a method whose worstTime(n) is linear in n. Estimate the effect of tripling n on run time—the actual time to execute the method in a particular computing environment. That is, estimate runTime(3n) in terms of runTime(n).
b. Suppose we have a method whose worstTime(n) is quadratic in n. Estimate the effect of tripling n on run time—the actual time to execute the method in a particular computing environment. That is, estimate runTime(3n) in terms of runTime(n).
c. Suppose we have a method whose worstTime(n) is constant. Estimate the effect of tripling n on run
time—the actual time to execute the method in a particular computing environment. That is, estimate
runTime(3n) in terms of runTime(n).  Get the solution of 3.7


3.8 This exercise proves that the Big-O families do not constitute a strict hierarchy. Consider the function f , defined for all non-negative integers as follows:
n, if n is even;
f (n) =
0, if n is odd
Define a function g on all non-negative integers such that f is not O(g) and g is not O(f ). Get the solution of 3.8


3.9 Show that O(n) = O(n + 7). Hint: use the definition of Big-O. Get the solution of 3.9


3.10 Show that if f (n) is polynomial in n, f (n) cannot be exponential in n. Get the solution of 3.10


3.11 Suppose, for some method, worstTime(n) = nn. Show that the method is an exponential-time method (that is, worstTime(n) is !(xn ) for some real number x >1.0). But show that worstTime(n) is not "(xn )—that is, Big Theta of xn—for any real number x >1.0.  Get the solution of 3.11


3.12 This exercise illustrates some anomalies of "(1).
a. Define f (n) to be 0 for all n ≥ 0. Show that f is not "(1), but f is "(0).
b. Define f (n) to be (n + 2)/(n + 1) for all n ≥ 0. Show that f is "(1)—and so can be said to be
“constant”—even though f is not a constant function. Get the solution of 3.12



PROGRAMMING EXERCISES
3.1 In mathematics, the absolute value function returns a non-negative integer for any integer argument. Develop a run method to show that the Java method Math.abs (int a) does not always return a non-negative integer.
Hint: See Programming Exercise 0.1.  Get the solution of 3.1

3.2 Assume that r is (a reference to) an object in the Random class. Show that the value of the following expression is not necessarily in the range 0 . . . 99:
Math.abs (r.nextInt()) % 100
Hint: See Programming Exercise 3.1. Get the solution of 3.2


3.3 Develop a run method that initializes a Random object with the default constructor and then determines the elapsed time for the nextInt() method to generate 123456789. Get the solution of 3.3


3.4 Suppose a method specification includes a Big-O estimate for worstTime(n). Explain why it would be impossible to create a unit test to support the Big-O estimate. Get the solution of 3.4


3.5 In the binarySearch method in Section 3.1.2, the average of low and high was calculated by the following expression
(low + high) >> 1
Compare that expression to
low + ((high - low) >> 1)
The two expressions are mathematically equivalent, and the first expression is slightly more efficient, but will return an incorrect result for some values of low and high. Find values of low and high for which the first expression returns an incorrect value for the average of low and high. Hint: The largest possible int value is Integer.MAX_VALUE, approximately 2 billion. Get the solution of 3.5

Data Structures and Java Collection Framework - William Collins - Chapter 2 Solutions

CONCEPT EXERCISES
2.1 The System class in java.lang has a class constant identifier that has been extensively used in Chapters 0, 1 and 2. What is that constant identifier? Why should a class’s constant identifiers be static ? Should a method’s constant identifiers be static ? Explain. Get the solution of 2.1


2.2 Create a catch block that will handle any exception. Create a catch block that will handle any input/output exception. Create a catch block that will handle any run-time exception. Get the solution of 2.2


2.3 What is wrong with the following skeleton?
try
{
...
} // try
catch (IOException e)
{
...
} // catch IOException
catch (FileNotFoundException e)
{
...
} // catch FileNotFoundException  Get the solution of 2.3


2.4 Suppose fileScanner is a Scanner object for reading from an input file, and printWriter is a Print
Writer object for writing to an output file. What will happen if, at the end of a program, you forget to close fileScanner ? What will happen if, at the end of a program, you do not close printWriter ? Get the solution of 2.4


2.5 What does “bottom-up” testing mean with respect to the classes in a project? Get the solution of 2.5


2.6 Suppose we create a two-dimensional array (literally, an array in which each element is an array). The following creates an int array with 50000 rows and 100000 columns:
int [ ][ ] a = new int [50000][100000];
If this code is executed, the program terminates abnormally, and the message is java.lang.OutOfMemoryError
Exception in thread "main"
Why wasn’t memory re-allocated by the garbage collector? Hypothesize whether this abnormal termination be handled with a try-block and catch-block. Test your hypothesis and explain. Get the solution of 2.6


2.7 Can a protected field be accessed outside of the class in which it is declared and subclasses of that class?
What does the following statement mean? “Subclassing represents more of a commitment than mere use.” Get the solution of 2.7


2.8 Arrays are strange objects because there is no array class. But an array object can call methods from the Object class. Determine and explain the output from the following code:
int [ ] a = new int [10];
int [ ] b = new int [10];
a [3] = 7;
b [3] = 7;
System.out.println (a.equals(b)); Get the solution of 2.8



PROGRAMMING EXERCISES
2.1 Develop the specification for a method that scans one line that is supposed to contain three double values and returns the largest. Throw all possible exceptions. Start with a stub for your method and create a test class to test your method. Re-test your method as you define it. Finally, include a main method and a run( ) method that calls the method you developed. Get the solution of 2.1


2.2 Develop the specification for a method that scans (what are supposed to be) double values from a file and returns the largest. Throw all possible exceptions. Start with a stub for your method and create a test class to test your method. Re-test your method as you define it. Finally, include a main method and a run( ) method that calls the method you developed. Get the solution of 2.2


2.3 Modify the run method for the Company class to scan from an input file and write to an output file. Include a re-prompt if either the input or output path is incorrect. Get the solution of 2.3


2.4 Hypothesize what is wrong with the following method:
public static boolean isEven (int i)
{
if (i % 2 == 0)
return true;
if (i % 2 != 0)
return false;
} // method isEven
Test your hypothesis by calling this method from a run( ) method. Can a try-block and catch-block
handle the problem? Explain. Get the solution of 2.4


2.5 Hypothesize the output from the following:
System.out.println (null + "null");
Test your hypothesis. Provide the code in the String class that explains why the output is what it is. Get the solution of 2.5


2.6 Give an example to show that private visibility is more restrictive than default visibility. Give an example to show that default visibility is more restrictive than protected visibility. Give an example to show that protected visibility is more restrictive than public visibility. In each case, test your code to make sure that the more restrictive choice generates a compile-time error message. No error message should be generated for the less restrictive choice. Get the solution of 2.6


2.7 Protectedness transfers across packages, but only within a subclass, and only for objects whose type is that subclass. For a bare-bones illustration, suppose we have class A declared in package APackage:
package APackage;
public class A
{
protected int t;
} // class A
Also, suppose that classes C and D are subclasses of A and that C and D are in a different package from A. Then within class D, the t field is treated as if it were declared in D instead of in A. Here are possible declarations for classes C and D:
import APackage.*;
public class C extends A { }
Programming Exercises 101
Class D is declared in another file. For each of the four accesses of t in the following declaration of class D,
hypothesize whether the access is legal or illegal:
import APackage.*;
public class D extends A
{
public void meth()
{
D d = new D();
d.t = 1; // access 1
t = 2; // access 2
A a = new A();
a.t = 3; // access 3
C c = new C();
c.t = 4; // access 4
} method meth
} // class D
Test your hypotheses by creating and running a project that includes the above files. Get the solution of 2.7


2.8 Re-do Programming Exercise 1.2 to print out the number of above-average salaries. Use an array field to hold the salaries, and assume there will be at most 10 salaries in the input. Get the solution of 2.8


2.9 Study the specification of the arraycopy method in the System class, and then write a short program that uses the arraycopy method to copy all the elements of an array to another array. Output the elements in the destination array to make sure the copying actually occurred. Get the solution of 2.9


2.10 Re-do Programming Exercise 2.8 if the input can contain an arbitrary number of salaries.
Hint: Start with an array of length 10. Whenever the number of salaries in the input exceeds the current length of the array field, create a new array of twice that length, copy the old array to the new array—see Programming Exercise 2.9—and then assign the new array (reference) to the old array (reference). Get the solution of 2.10


2.11 According to the full method specification in the Object class, any override of the Object class’s equals method should satisfy the following five properties:
1. reflexivity, that is, for any non-null reference x,
x.equals (x)
should return true.
2. symmetry, that is, for any non-null references x and y,
x.equals (y)
should return the same result as
y.equals (x)
3. transitivity, that is, for any references x, y and z if
x.equals (y)
returns true, and
y.equals (z)
returns true, then
x.equals (z)
should return true.
4. consistency, that is, for any non-null references x and y, multiple invocations of
x.equals (y)
should consistently return true or consistently return false, provided no information used in equals
comparisons on the objects is modified.
5. actuality, that is, for any non-null reference x,
x.equals (null)
should return false.
For the FullTimeEmployee class’s equals method (see Section 2.7), provide examples to support the
claim that the equals method satisfies those five properties. You are not being asked to prove that the
FullTimeEmployee class’s equals method satisfies those properties. Get the solution of 2.11


2.12 Create and run a test class for the equals method defined in Section 2.7 for the FullTimeEmployee class. Get the solution of 2.12