Tomcat web server - Chapter 6 Methods 311 Fig. 6.23 The Towers

Chapter 6 Methods 311 Fig. 6.23 The Towers of Hanoi for the case with four disks. Write an applet to solve the Towers of Hanoi problem. Allow the user to enter the number of disks in a JTextField. Use a recursive towermethod with four parameters: a) the number of disks to be moved, b) the peg on which these disks are initially threaded, c) the peg to which this stack of disks is to be moved, and d) the peg to be used as a temporary holding area. Your program should display in a JTextAreawith scrolling functionality the precise instructions it will take to move the disks from the starting peg to the destination peg. For example, to move a stack of three disks from peg 1 to peg 3, your program should print the following series of moves: 1 . 3 (This notation means move one disk from peg 1 to peg 3.) 1 . 2 3 . 2 1 . 3 2 . 1 2 . 3 1 . 3 6.38 Any program that can be implemented recursively can be implemented iteratively, although sometimes with more difficulty and less clarity. Try writing an iterative version of the Towers of Hanoi. If you succeed, compare your iterative version with the recursive version you developed in Exercise 6.37. Investigate issues of performance, clarity and your ability to demonstrate the correctness of the programs. 6.39 (Visualizing Recursion) It is interesting to watch recursion in action. Modify the factorial method of Fig. 6.12 to print its local variable and recursive-call parameter. For each recursive call, display the outputs on a separate line, and add a level of indentation. Do your utmost to make the outputs clear, interesting and meaningful. Your goal here is to design and implement an output format that helps a person understand recursion better. You may want to add such display capabilities to the many other recursion examples and exercises throughout the text. 6.40 The greatest common divisor of integers xand yis the largest integer that evenly divides into both xand y. Write a recursive method gcdthat returns the greatest common divisor of xand y. The gcdof xand yis defined recursively as follows: If yis equal to 0, then gcd(x,y)is x; otherwise, gcd(x,y)is gcd(y,x%y), where %is the modulus operator. Use this method to replace the one you wrote in the applet of Exercise 6.28. Copyright 1992 2002 by Deitel & Associates, Inc. All Rights Reserved. 7/3/01

Leave a Reply