Java Reference
In-Depth Information
A stack of n disks of decreasing size (from bottom to top) is placed on one of three
posts. The task is to move the disks one at a time from the first post to the second.
To do this, any disk can be moved from any post to any other post, subject to the
rule that you can never place a larger disk over a smaller disk. The (spare) third
post is provided to make the solution possible. Your task is to write a recursive
static method that gives instructions for a solution to this problem. We do not
want to bother with graphics, so you should output a sequence of instructions
that will solve the problem. The number of disks is a parameter to the method.
Hint: If you could move up n-1 of the disks from the first post to the third post
using the second post as a spare, the last disk could be moved from the first post
to the second post. Then, by using the same technique (whatever that may be),
you can move the n-1 disks from the third post to the second post, using the
first disk as a spare. There! You have the puzzle solved. You have only to decide
what the nonrecursive case is, what the recursive case is, and when to output
instructions to move the disks.
8. Write a recursive method named contains with the following header:
public static boolean contains(String haystack, String needle)
The method should return true if needle is contained within haystack and
false if needle is not in haystack . For example,
contains("Java programming", "ogr") should return true
contains("Java programming", "grammy") should return false
You are not allowed to use the substring method to find a match.
9. The program to recursively find a file in Display 11.11 stops searching when the
first match is found. Modify the program so that if there are multiple files with the
same name in different directories, then all matching files are found and output.
The simplest way to do this is to output all matches in the recursive method with
a print statement. For a more challenging version, modify the method to return
an array of Strings containing the pathnames of all matching files. It can return
null or an empty array if there are no matches. Feel free to create additional helper
classes if needed (e.g., to manage the number of items in the array of Strings). In
Chapter 14, we will introduce ArrayLists, which make it easier to create an array-
like structure with an arbitrary number of entries.
10. Given the definition of a 2D array such as the following,
String[][] data = {
{"A", "B"},
{"1", "2"},
{"XX","YY","ZZ"}
};
Search WWH ::




Custom Search