Recursive aspect of the Tower of Hanoi problem.

Right now I am a CS student in high school. I am going ahead of the class and my teacher recommended that I learn recrusion for Java.
Can somebody provide a trace or a link to a trace for this. I have been spending the last two days trying to understand the recursion aspect of this problem and I am stuck.
I tried to use: http://www.cs.cmu.edu/~cburch/survey/recurse/hanoiex.html but it didn't help
Or if somebody could just notate the part of the code so I would be able to understand it. I understand basic recursion, but I am exploring stuff that is in the same chapter such as the tower problem and Recursive Premutation (I have no idea how that works).
Here is the code my textbook provided:
private void moveTower (int numDisks, int start, int end, int temp)
          if (numDisks == 1)
               moveOneDisk (start,end);
          else
               moveTower(numDisks-1, start, temp, end);
               moveOneDisk (start, end);
               moveTower(numDisks-1, temp, end, start);
Thanks for your time.
Edit: (forgot the moveOneDisk method)
private void moveOneDisk (int start, int end)
          System.out.println("Move one disk from " + start + " to " + end);
          count++; //Seperate variable to keep track of the nubmer of moves
     }

First of all, I love the towers of hanoi problem... I still think its so cool.
So you start off with a number of pegs on one spindle
x
x
x
x
A  B  CAnd you want to more the blocks from A to C.
The steps are:
1. move the n-1 blocks from A to B,
2. move the bottom block from A to C
3. move n-1 blocks from B to C
But, you should see that in doing steps 1 and 3, you are doing the towers of hanoi problem for a smaller tower, which makes it recursive.
So you need a base case - moving one block. Then you need to write a recursive function that does the steps I've laid out.
Good luck!

Similar Messages

  • Tower of hanoi

    where i can find pseudo code or regular code (as simple as possible) for the tower of hanoi?

    Here is one possiblility that works:
    public class TowerHan {
    public static void main(String[] args) {
    TowerHan towerHan=new TowerHan();
    towerHan.towerOfHanoi();
    int nToMove,sorcPole,destPole; int nPoles;
    int[][] poles; int[] counts;
    private void towerOfHanoi() {
    nPoles=3; sorcPole=0; destPole=2;
    for(nToMove=5;nToMove>0;nToMove-=1) {
    poles = new int[nPoles][nToMove];
    for(int p=0;p<nPoles;p++)for(int j=0;j<nToMove;j++)poles[p][j]=(p==0)?nToMove-j-1:0;
    counts = new int[nPoles]; for(int p=0;p<nPoles;p++)counts[p]=0; counts[0]=nToMove;
    System.out.println(nPoles+" poles are numbered 0 to "+(nPoles-1));
    System.out.println(nToMove+" rings are numbered "+(nToMove-1)+" downto 0, big to small");
    prinPoles();
    move(nToMove,sorcPole,destPole);
    private void prinPoles() {
    for(int p=0;p<nPoles;p++) {
    for(int j=0;j<nToMove;j++)
    if(j<counts[p])System.out.print(poles[p][j]);else System.out.print(" ");
    System.out.print(" , ");
    } System.out.println();
    private void move(int nToMove, int sorcPole, int destPole) {
    if (nToMove==1) {
    poles[destPole][counts[destPole]++]=poles[sorcPole][--counts[sorcPole]];
    prinPoles();
    } else { //nPoles-sorcPole-destPole is the spare pole: 3-2-0=1,3-2-1=0,3-1-0=2;
    move(nToMove-1,sorcPole,nPoles-sorcPole-destPole);
    move(1,sorcPole,destPole);
    move(nToMove-1,nPoles-sorcPole-destPole,destPole);
    //To move n from A to C, move n-1 from A to B, one from A to C, n-1 from B to C;

  • HT1420 No longer authorized to enter the account was used to five devices have exhausted all attempts to please you to the solution to this problem I reside in recursion and I'm not good at English Language

    No longer authorized to enter the account was used to five devices have exhausted all attempts to please you to the solution to this problem I reside in recursion and I'm not good at English Language 

    MMS will be available for the 3G and 3GS in two weeks - on Friday, September 25th - likely with a carrier update made available via iTunes.
    In the interim - for the next two weeks, ask the sender of an MMS to address the MMS to an email address that you access with the iPhone's Mail client - the sender will enter your email address in the To: field for the MMS instead of your cell phone number with area code. The MMS will be received by you as an email with the photo as an attachment. This will give you the sender's cell phone MMS email address. Add this email address to the contact's info in your iPhone's address book. If you want to send an email with a photo attached as an MMS to this person, address the email to their cell phone MMS email address. The email with the photo attached will be received as an MMS.
    This will be required for another two weeks.

  • 3G no longer working at office. Tower, or phone problem?

    For about a week, the 3G data connection on my iPhone has not been working from my office. I'm not sure but this might have happened after my upgrade to iOS 4.3.3. I used to get a slow but steady data rate, both indoors and out. Now, I get 3 coverage indicator bars. Voice works fine, but data only works if I switch off 3G and use EDGE.
    I really don't think it's hardware, because it works fine at home and elsewhere. I've reset network settings and performed soft and hard reboots of the phone.
    AT&T customer support showed no indication of being able to resolve this problem. My AT&T Blackberry is working fine, for what that's worth.
    Does anyone have any other suggestions on how to troubleshoot the phone?
    Or a better way to reach AT&T to troubleshoot the tower/network?
    Thanks!

    FIRST call AT&T support and have them reset your account settings. The most likely cause is that data has been disabled on your account (call; the droids in the store don't know much; the techies on the help desk generally do).

  • After a power outage my usb ports on the back of the tower do not recognise the apple usb keyboard upon start up. How do I fix this issue?

    I have a Mac Pro 5.1 and after a power outage my usb ports on the back of the tower do not recognise the apple usb keyboard upon start up. If I leave the plug out and then insert the keyboard after start up it works fine. The same happens with the front usb ports. How do I fix this issue?

    System.log says USB related message?
    Resetting SMC as well as NVRAM could solve the problem.
    Intel-based Macs: Resetting the System Management Controller (SMC)
    About NVRAM and PRAM

  • Recursion or not Recursion: That is the question.

    I am currently in an AP Comp. Science course online. Just finished a lesson on recursion, and while somewhat confused, I thought that I had kind of got the concept. Turned in to my teacher a program I was sure was a recursive program. He sent back saying that I hadn't done the right "pattern" for recursion. After a bit research I think he's mistaken, but before I point it out to him I want to make sure my claims are correct. If anyone would be so kind as to check my simple program and confirm or refute that would be great. The program is supposed to take in a string and reverse it. I've added output in the Reverse method which makes me think he's mistaken.
    * StringReverse takes a string object and reverses it.
    * @author Joshua Rosenauer
    * @version 12/16/05
    import chn.util.*;
    class StringReverse
        public String Reverse (String word)
            int length;
            String reversedWord = "";
            length = word.length();
            if(length > 0)
                  System.out.println ("This is the word being entered: " + word);
                  reversedWord = word.charAt(length-1)+Reverse(word.substring(0,length-1));
                  System.out.println ("This is the word leaving: " + reversedWord);
              return reversedWord;
         public static void main(String[] args)
             ConsoleIO keyboard = new ConsoleIO ();
             StringReverse reverser = new StringReverse ();
             char answerChar;
             do
                 System.out.print ("Enter a word (press Q/q to quit): ");
                 String word = keyboard.readToken ();
                 answerChar = word.charAt(0);
                 String newWord = reverser.Reverse(word);
                 System.out.println ("New word: " + newWord);
             while ((answerChar != 81)&&(answerChar != 113));
    }

    Huh? You can unwind any recursive algorithm.Sure. But the way the OP posted, you could replace without adding a stack. The way I suggested you'd still need a stack.
    The
    coolness is if you keep pushing the first element
    onto the stack and then unwind LIFOThe code given is using the stack.I guess we're just not clicking over this. Oh well.
    Anyway, here's my absolute favorite recursive thingie - the towers of hanoi. The way it works is such a thing of beauty!
    http://www.cut-the-knot.org/recurrence/hanoi.shtml

  • Mac G4 Tower Model: M8493 Problems

    Hi all:
    I got this tower from a friend, who told me it was a stable machine. I had my suspicions, and they were proved correct when I tried booting the machine.
    I swapped out the 80gb Seagate H.D.D. with a W.D. 250gb. I was also having serious problems opening the drive, so I had to use a paper clip, with the system shut down, and insert it into the hole at the left, lower corner of the front end of the drive.
    However, I took my copy of Leopard and placed it in the tray and this is what happened: I received a kernel panic, and at the bottom of the monitor a bunch of data lines began appearing: R1= 0x23730670; XCP = 0x0000000C, etc.
    Prior to this, I tried to install the OS and it stuck at the Grey Mac Screen with the Apple symbol. The circular, load was revolving for a long time until it stopped; however, I left the machine on for over 10 hours, and it was locked at this state.
    I'm not sure if the optical drive is malfunctioning or there is another issue(s). I'm running the tower off a Toshiba monitor with standard PC peripherals.
    Any help or suggestions would be greatly appreciated.
    Thanks in advance,
    Steve

    Thanks for your post, Allan. Yeah, it's a retail OS X disc; not the grey disc that comes with Apple computers. I knew that wouldn't work.
    It's the 2002 G4 model I believe. I checked the OS X installation on my G5 Quad PPC and it works fine. I also have a drive cleaning disc, as when I opened the computer, it was a complete mess: filled with dust and debris, but nothing that some compressed air couldn't take care of - well, visually at least.
    The serial for this G4 is: XB216*M8H. I went to the macmedic site -- I think that was the site -- entered the serial, and it told me that it had a 1.07Ghz processor. Not entirely certain about the number, but I know it exceeded 1Ghz, which is odd, as I haven't seen G4 models with that speed processor in my own searches.
    Yeah, I figured the battery was probably shot, too. So your advice on getting another would be optimal; however, I want to really hone in on the exact issue(s).
    According to the jumper identifications on the W.D. 250gb drive, no jumper indicates master. I know that isn't the issue due to the fact that when I start the machine without the OS X disc in the drive bay, it goes to the blue screen with mac-finder face and the question mark, which indicates it's picking up the H.D.D.
    The computer did boot to its desktop with the old H.D.D., but it would list some hardware issues and the gray, multilingual screen would come up -- English, French and German -- prompting me to restart.
    I may have left a few of your questions out, as I'm kind of in the middle of swapping a drive from a laptop.
    Please let me know if you have any further advice. Much appreciated, Allan.
    Best,
    Steve
    <Serial Number Edited by Host>

  • Each time I try to synch photos from my Windows 7 PC to my iPad2, iTunes stops working, and the error report says Problem Event Name:     APPCRASH   Application Name:     iTunes.exe   Application Version:     10.3.1.55   Application Timestamp:     4deec35

    Each time I try to synch photos from my Windows7 PC to my iPad2, iTunes stops working and the error message is:
    Problem Event Name:                          APPCRASH
      Application Name:                             iTunes.exe
      Application Version:                           10.3.1.55
      Application Timestamp:                    4deec351
      Fault Module Name:                          ntdll.dll
      Fault Module Version:                        6.1.7601.17514
      Fault Module Timestamp:                 4ce7ba58
      Exception Code:                                  c0000005
      Exception Offset:                                0002e3fb
      OS Version:                                          6.1.7601.2.1.0.768.3
      Locale ID:                                             1033
      Additional Information 1:                  0a9e
      Additional Information 2:                  0a9e372d3b4ad19135b953a78882e789
      Additional Information 3:                  0a9e
      Additional Information 4:                  0a9e372d3b4ad19135b953a78882e789
    I reloaded iTunes 10 (64 bit) successfully, but the problem remains the same.
    Any suggestions?

    I looked in the folder from which I want to synch photos, but there is no such thing as an "ipod photo cache" in that folder, or sub-folders, as suggested in the link which you were nice enough to provide.
    I have also tried removing photos from my iPad2 Photos App, and "iTunes has stopped working" shows up  again as soon as I click on the "Synch photos from" button.

  • With my i phone 4 , the Push notifications doesn't work for apps like (fb viber , whatsapp etc ) it only works for the official apps like message  even when im using the phone, has  this probleme with the iOs 6.0.1 and also with the iOs 6.1

    With my i phone 4 , the Push notifications doesn't work for apps like (fb viber , whatsapp etc ) it only works for the official apps like message  even when im using the phone, has  this probleme with the iOs 6.0.1 and also with the iOs 6.1

    This isn't an issue. Notice the screen prior to the one that shows usage has an iCloud section and a Manage Storage button. For this button to activate ios needs to download a few kb from icloud. Switching back to this screen forces ios to download those few kb.

  • HT204152 I am unable to update my App  store Updations. the reason being billing problem asking to update payment method.many times i updated my credit card details but refusing from the system .how can i update my app store updations like  Face book etc.

    I am unable to update my App  store Updations. the reason being billing problem asking to update payment method.Many a  times i updated my credit card details but refusing from the system .how can i update my app store updations like  Face book etc....Using ! phone 6plus  .IOS8.3

    What do you mean by 'refusing from the system', if you are getting an error message then what does it say ?
    For a credit card to have a chance of being accepted it needs to be registered to the same name and address (including format and spacing etc) that you have on your iTunes account, and have been issued by a bank in the country where you and your iTunes account are. If it is and if you are getting a 'declined' message then you could check with the card issuer to see if it's them that are declining it, and if not then try contacting iTunes Support (these are user-to-user forums) and see if they know why it's being declined : http://www.apple.com/support/itunes/contact/ - click on Contact iTunes Store Support on the right-hand side of the page, then Purchases, Billing & Redemption
    If when trying to download you are getting a message about a 'problem with a previous purchase' then that implies that iTunes wasn't able to collect the money for your last purchase. If that is the case then you won't be able to download anything else (including app updates) until you've paid off what you owe : Pay an unpaid balance in the iTunes Store - Apple Support
    If you aren't getting the 'problem with a previous purchase' message then try logging into your account (not when trying to download something) and see if you get the 'none' option so that you can remove the card's details and be able to download updates to your apps : Change or remove your payment information from your iTunes Store account (Apple ID) - Apple Support

  • We are unable to open a Pages 5.0.1 document in Pages 4.2 and retain ability to edit all aspects of the document. I have tried saving the 5.0.1 version as Pages '09 and am still unable to open it in the earlier version of pages. Help?

    We are unable to open a Pages 5.0.1 document in Pages 4.2 and retain ability to edit all aspects of the document. I have tried saving the 5.0.1 version in Pages '09 but am still unable to open it in the earlier version of pages. Help?

    No, it isn't. Pages 5 isn't compatible with Pages 4.3 as it is lacking more than 90 features that Pages 4 has. So when you open a Pages 4 document in Pages 5 only the simplest documents will look the same in Pages 5.
    Pages 4 can't open Pages 5 documents at all!! You have to export back to Pages 09 as I said above.
    You probably will be more happy if you just use Pages 4 (Pages 09). There are many threads in this forum that describes the lack of compatibility between the two versions. Pages 5 is in my view not Pages anymore.
    If you don't desperately need Pages 5 for moving documents over iCloud to new iOs devices don't use it.

  • An APP that points to the tower you are currently using

    1/5/2012
    All,
    Here is a really nifty or shall I say really cool or maybe helpful APP.  See attached screen shot.
    We were in Catalina State park in Tucson, AZ in our Motorhome and another motorhomer told me about this Android APP.  It is called OpenSignalMaps. 
    This APP will bring up a map of where you are and then show your location on the map.  Then it will "take its time" finding the cell tower to which you are currently connected and draw a red colored line between your location and the tower.
    All the local streets are shown on the map.  It seems to work best if all 3 of your GPS's are ON but it also did work well when I turned OFF the Verizon GPS  leaving only the other two ON.
    With the rather weak Verizon 3G only signal at Catalina State park it took about 5-9 minutes to find everything and draw the red line. 
    OTOH, when I drove through Tucson with it's stronger Verizon 3G/4G signal it found the first tower in about 2 minutes and as we were driving I watched it change to a different tower three times.  The red lind just jumps in a new direction...cool.  You can move the map around to see both ends of the red line it you uncheck "Turn OFF auto cenetring"  because if you don't it will keep centering on your location.
    Be patient it is a bit slow but you won't use it that often; although, it might be nice to confirm which tower you use at your home, business location, or ???.
    When I arrived home I just started it, set the phone down, went to the kitchen to get a cup of coffee, and about 5 or so minutes later it had found the tower.
    It also shows the RSSI (name of the tower).
    It's free so if it's to slow for you just uninstall it. 
    JerryF

    If your location on the map is off press the MENU button (lower left corner of your phone).  Then when the next screen appears Touch "my location" and it will move the your blue colored location ICON to your current location.
    Also, you can touch the tower ICON to see the tower's SSID, SID, and Received signal strength.  WIKI has good definitions for these acronyms.  If you go to CELLS (top of screen) you can also see the RSSI and the overview shows the signal strength in %.
    JerryF

  • I bought an IPhone 5 in the US last Jan. The bettery was tested problem at my local Apple Store in Shanghai, China. Must I send it to the store where I bought it or Can any Apple Store in the US help me repair it? Thank you.

    Recently, my Iphone shuts down at 50%+ bettery. My local Apple Store told me that the bettery was tested problem and needs to be repaired or changed. Since the phone is still under a year warranty, I was suggested to return it to the US Apple Store for help. Please let me know if I can send it to any store in the US or the store where I bought. Also, I don't find the email receipt. Will it be a problem for repair? Your quick response will be very appreciated. Thank you.

    One more question. Can it be down without the receipt? If yes, I will send the phone to US immediately before warranty expired. Thank you.

  • I just updated my latest java but the update is causing problems with some externale devices. So i would like to uninstall this latest java update and get back the previous one. That should solve to problems with my external device

    i just updated my latest java but the update is causing problems with some external devices. So i would like to uninstall this latest java update and get back the previous one. That should solve to problems with my external device.
    Is this possible and how do i do that?
    Anyone who responds thanks for that!
    Juko
    I am running
    Hardware Overview:
      Model Name:          Mac Pro
      Model Identifier:          MacPro1,1
      Processor Name:          Dual-Core Intel Xeon
      Processor Speed:          2,66 GHz
      Number of Processors:          2
      Total Number of Cores:          4
      L2 Cache (per Processor):          4 MB
      Memory:          6 GB
      Bus Speed:          1,33 GHz
      Boot ROM Version:          MP11.005D.B00
      SMC Version (system):          1.7f10
      Serial Number (system):          CK7XXXXXXGP
      Hardware UUID:          00000000-0000-1000-8000-0017F20F82F0
    System Software Overview:
      System Version:          Mac OS X 10.7.5 (11G63)
      Kernel Version:          Darwin 11.4.2
      Boot Volume:          Macintosh HD(2)
      Boot Mode:          Normal
      Computer Name:          Mac Pro van Juko de Vries
      User Name:          Juko de Vries (jukodevries)
      Secure Virtual Memory:          Enabled
      64-bit Kernel and Extensions:          No
      Time since boot:          11 days 20:39
    Message was edited by Host

    Java 6 you can't as Apple maintains it, and Java 7 you could if you uninstall it and Oracle provides the earlier version which they likely won't his last update fixed 37 remote exploits.
    Java broken some software here and there, all you'll have to do is wait for a update from the other parties.

  • I had an iphone 4 and when I downloaded the IOS7 started having problems. Gone the phone keypad, could not type more names of my contacts in the phone search. I decided to buy the iphone 5S and since downloaded the IOS7.1.2 the search of yo

    I had an iphone 4 and when I downloaded the IOS7 started having problems. Gone the phone keypad, could not type more names of my contacts in the phone search. I decided to buy the iphone 5S and since downloaded the IOS7.1.2 the search of your phone contacts it takes to open or write

    dedegodoy wrote:
    I decided to buy the iphone 5S and since downloaded the IOS7.1.2 the search of your phone contacts it takes to open or write
    What does that mean? What is your technical support question?

Maybe you are looking for