Towers of Hanoi

I need your help, guys. I am teaching myself Java with Dietel and Dietel's book "Java: How to Program" (3rd ed). I am trying to do the Towers of Hanoi applet in chapter 6. I am so confused about the order in which I pass my pegs! Is there any way I could obtain the code for just the tower method? Could someone post it or something? Your help will be greatly appreciated.

Hi,
Here is the link with the code for the "Tower" method.
http://javaboutique.internet.com/Tower/source.html
Hope this helps.
Roopasri Vittal
Developer Technical Support
Sun Microsystems
http://sun.com/developers/support

Similar Messages

  • Anyone recommend a Linux Towers of Hanoi game?

    I can find lots of Towers of Hanoi solvers, but I can't find an implementation of the actual game itself. Can anyone recommend one?

    Lexion wrote:Are there any that are text-only? I don't much care for graphics...
    Google it with curses:
    http://pauls-pc-repair.com/sudoku/index.php?page=Tower
    I tried it out. It works fine, just one make and ./hanoi
    Edit: BTW tarbomb.
    Last edited by Procyon (2009-01-29 02:45:09)

  • Towers of Hanoi 4-peg

    As an assignment, I must create a program that solves the towers of hanoi problem with 4 pegs for n-disks.
    I used recursion to move k=n/2 disks to an aux1 peg using all four pegs.
    then i used the 3-peg algorithm to move the remain n-k disks to the target peg.
    then i moved the k disks to the target peg using all four pegs.
    This solution works however, the bonus question is to find the most efficient algorithm. For 3, 4, and 5 disks the solution i currently have solves the problem in the minimum amount of steps. However when n=6 my solution takes 21 moves whereas I read the optimal number of moves is 17. Could anyone suggest a more efficient algorithm?
    Thanks

    AmarilloSlim I assumed your reply was ironic. If it
    wasn't, well, you're wellcome. -:)
    Of course, he couldn't possibly be referring to my (terribly pithy) link... :oP

  • Program To Implement Towers Of Hanoi

    Hi Everybody,
    Can any one help me in writing code for Towers of Hannoi program in java?????????
    Regards
    Shyam

    prometheuzz wrote:
    JosAH wrote:
    Darryl.Burke wrote:
    ps. wasn't there a cute recursive link, replied by Yawmark in this thread?No, that was in two other threads. Oh, or did you mean this?I don't know yet, I'm still following your links.
    kind regards,
    Jos ;-)Then how did you get here? Are you in a quantum state?If you consider using multiple windows a quantum state: yes I am a chocolate quark!
    kind regards,
    Jos ( or not ;-)

  • Towers of hanoi    (please explain)

    /*the Method below works Fine, but i don't know how it works.It would be much appreciated if anyone could explain it line by line. please be clear cause i realy need to know the meaning/work behind it. I have marked the lines i need to know clearly 1,2,3.
    PLEASE EXPLAIN AS IF YOU ARE EXPLAINING TO A GRADE 5 CHILD
    I AM REALY NEW AT THIS.
    static void H_dohanoi(int n, int t, int f, int u)
    if (n > 0) {
    H_dohanoi(n-1, u, f, t); // (1)
    H_moveit(f, t); //(2)
    H_dohanoi(n-1, t, u, f);//(3)
    YOUR HELP IS MUCH APPRICIATED. keep on coding well!!

    livinloud wrote:
    I think it explains it all
    wikipedia
    I think the animated GIF suffices!

  • 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!

  • Swing components in applet not working in web browser

    Hi Guys,
    I've created an applet which makes use of some swing components, but unfortunately, not all of them function properly in my web browser (internet explorer or Mozilla Firefox). Its mainly the buttons; the last buttons works and displays the correct file within the broswer, but the first 5 buttons do not work...
    any help please on how I can sort this problem out?
    Heres the code for my applet:
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import java.applet.*;
    public class MainAppWindow extends JApplet
    int gapBetweenButtons = 5;
    final JPanel displayPanel = new JPanel(new BorderLayout());
    public void init()
       //Panel for overall display in applet window.
       JPanel mainPanel = new JPanel(new BorderLayout());
       mainPanel.add(new JLabel(new ImageIcon(getClass().getResource("images/smalllogo2.gif"))),BorderLayout.NORTH);
       //sub mainPanel which holds all mainPanels together.
       JPanel holdingPanel = new JPanel(new BorderLayout());
       //Panel for displaying all slide show and applications in.
       displayPanel.setBackground(Color.white);
       displayPanel.add(new JLabel(new ImageIcon(getClass().getResource("images/IntroPage.jpg"))),BorderLayout.CENTER);
       displayPanel.setPreferredSize(new Dimension(590,400));
       JPanel buttonPanel = new JPanel(new GridLayout(6,1,0,gapBetweenButtons));
       buttonPanel.setBackground(Color.white);
       JButton button1 = new JButton("User guide");
       button1.addActionListener(
         new ActionListener() {
              public void actionPerformed(ActionEvent e)
                   if(displayPanel.getComponents().length > 0)displayPanel.removeAll(); // If there are any components in the mainPanel, remove them and then add label
                   displayPanel.setBackground(Color.white);
                   displayPanel.add(new JLabel(new ImageIcon("images/UserGuide.jpg")));
                   displayPanel.revalidate(); // Validates displayPanel to allow changes to occur onto it, allowing to add different number images/applicaions to it.
       JButton button2 = new JButton("What is a Stack?");
       button2.addActionListener(
       new ActionListener() {
               public void actionPerformed(ActionEvent e)
                   if(displayPanel.getComponents().length > 0)displayPanel.removeAll();
                   displayPanel.setBackground(Color.white);
                   displayPanel.add(new JLabel(new ImageIcon("images/WhatIsAStack.jpg")));
                   displayPanel.revalidate();
       JButton button3 = new JButton("STACK(ADT)");
       button3.addActionListener(
       new ActionListener() {
             public void actionPerformed(ActionEvent e)
                   if(displayPanel.getComponents().length > 0)displayPanel.removeAll();
                   displayPanel.setBackground(Color.white);
                   displayPanel.add(new JLabel(new ImageIcon("images/StackADT.jpg")));
                   displayPanel.revalidate();
       JButton button4 = new JButton("Stacks in the Real World");
       button4.addActionListener(
       new ActionListener() {
             public void actionPerformed(ActionEvent e)
                   if(displayPanel.getComponents().length > 0)displayPanel.removeAll();
                   displayPanel.setBackground(Color.white);
                   displayPanel.add(new JLabel(new ImageIcon("images/StacksInTheRealWorld.jpg")));
                   displayPanel.revalidate();
       JButton button5 = new JButton("DEMONSTRATION");
       button5.addActionListener(
       new ActionListener() {
             public void actionPerformed(ActionEvent e)
                 if(displayPanel.getComponents().length > 0)displayPanel.removeAll();
                 Demonstration app = new Demonstration();
                 JPanel appPanel = app.createComponents();//gets the created components from Demonstration application.
                 appPanel.setBackground(Color.pink);
               displayPanel.add(appPanel);
               displayPanel.revalidate();
       JButton button6 = new JButton("Towers Of Hanoi");
       button6.addActionListener(
       new ActionListener() {
             public void actionPerformed(ActionEvent e)
                     if(displayPanel.getComponents().length > 0)displayPanel.removeAll();
                     TowerOfHanoi app = new TowerOfHanoi();
                     JPanel appPanel = app.createComponents();//gets the created components from Towers of Hanoi
                     JPanel mainPanel = new JPanel();//panel used to centralise the application in center
                     mainPanel.add(appPanel);
                     mainPanel.setBackground(Color.pink); //sets mainPanel's background color for 'Towers Of Hanoi'
                     displayPanel.add(mainPanel);
                     displayPanel.revalidate();
       //adding buttons to the buttonPanel.
       buttonPanel.add(button1);
       buttonPanel.add(button2);
       buttonPanel.add(button3);
       buttonPanel.add(button4);
       buttonPanel.add(button5);
       buttonPanel.add(button6);
       JPanel p = new JPanel(); // Used so that the buttons maintain their default shape
       p.setBackground(Color.white);
       p.add(buttonPanel);
       holdingPanel.add(p,BorderLayout.WEST);
       holdingPanel.add(displayPanel,BorderLayout.CENTER);
       //Positioning of holdingPanel in mainPanel.
       mainPanel.add(holdingPanel,BorderLayout.CENTER);
       //indent mainPanel so that its not touching the applet window frame.
       mainPanel.setBorder(BorderFactory.createEmptyBorder(10,20,10,20));
       mainPanel.setBackground(Color.white);
       mainPanel.setPreferredSize(new Dimension(850,600)); //size of applet window
       mainPanel.setOpaque(false); // Needed for Applet
       this.setContentPane(mainPanel);
    }

    Thanks for the response. I don't quite understand what you're talking about though. I have, in my humble knowledge, done nothing with packages. I have put the applet class (WiaRekenToolActiz.class is the applet class) in the jar file wia_actiz_archive.jar. From what I read on the tutorial, java looks for the applet class in all the jar files specified. Since I put my CODEBASE as the main url, I thought it baiscally didn't matter where you out the html file.
    I shall include the complete html page complete with applet tag to perhaps illuminate a bit more what I mean...
    <html>
    <head>
    <title>Wia Rekenmodule hello!</title>
    </head>
    <body bgcolor="#C0C0C0">
    <applet
    CODEBASE= "http://www.creativemathsolutions.nl/test"
    ARCHIVE= "Actiz/wia_actiz_archive.jar, Generic/wia_archive.jar"
    CODE="WiaRekenToolActiz.class" 
    WIDTH=915 HEIGHT=555
    >
    <PARAM NAME = naam VALUE = "Piet Janssen">
    <PARAM NAME = gebdag VALUE = "01">
    <PARAM NAME = gebmaand VALUE = "06">
    <PARAM NAME = gebjaar VALUE = "1970">
    <PARAM NAME = geslacht VALUE = "man">
    <PARAM NAME = dienstjaren VALUE = "10">
    <PARAM NAME = salaris VALUE = "56500">
    <PARAM NAME = deeltijdpercentage VALUE = "100">
    <PARAM NAME = accountnaam VALUE = "Zorginstelling 'De Zonnebloem'">
    </applet>
    </body>
    </html>

  • Painting Graphics from an Array

    I have a GUI that displays the Towers of Hanoi solution in a JPanel. Everything actually works except for a slight repainting issue.
    Currently I am overriding the paint() function, I know that for my purpose using paintComponent() would probably be the better route, however that's not my issue...
    The images (disks) in my JPanel are not redrawing properly, and I have no idea why...
    Basically:
    - I call setup() to set the number of disks and the co ordinates they should be drawn. (store them in an array)
    - I call moveDisk() to change the co ordinates of each disk as they are being moved.
    - then drawDisk() is called to go through the array of disks and print them.
    currently paint() calls drawDisk() in order to display the current position of all the disks.
    It seems to work fine for the first 2 moves, then disks start disappearing until there is one (the last disk) left...BUT if I print the co ordinates of the disks they seem to be correct, just not drawing.
    could someone take a look at my code and see what is wrong?
    below is the meat of the code, minus the GUI:
        public class HanoiFrame extends javax.swing.JFrame {
        private static final int STATE_SETUP = 0;
        private static final int STATE_ANIMATE = 1;
        private static final int POLE_AREA_HEIGHT = 356;
        private static final int POLE_AREA_WIDTH = 205;
        private static final int DISK_ARC_HEIGHT = 15;
        private static final int DISK_ARC_WIDTH = 15;
        private static final int DISK_HEIGHT = 23;
        private static final int MAX_DISKS = 10;
        private static final int MAX_ANIMATION_DELAY = 30000;
        private static final int MAX_PHYSICAL_DELAY = 100000;
        private static final int MIN_DISKS = 1;
        private static final int MIN_ANIMATION_DELAY = 1;
        private static final int MIN_PHYSICAL_DELAY = 1;
        private static final int EMPTY_CELL_VALUE = -1;
        private static final int CELL_HEIGHT = 25;
        private static final int COLUMNS = 3;
        private static final int ROW = 11;
        private  static final int MILLISECONDS_PER_SECOND = 1000;
        private final static String newline = "\n";
        private static Disk[] disks;
        private static Disk newDisk;
        private static int[][] diskCells;
        public static  int startX = 2;
        public static  int startY = 340;
        public static int setDiskAmount = 0;
        public static int setAnimationDelay = 0;
        public static int  setPhysicalDelay = 0;
        public static int  moveNumber = 0;
        public static int intMovesLeft = 0;
        private boolean  buttonPressed = false;
        private double movesLeft = 0;
        private int windowState = 0;
        /** Creates new form HanoiFrame */
        public HanoiFrame() {
            initComponents();
            /* initialize the "poles" to hold a certain number of "cells */
            this.diskCells = new int[ROW][COLUMNS];
            for (int row = ROW - 1;row >= 0; row--) {
                for (int col = 0;col < COLUMNS ; col++) {
                    diskCells[row][col] = EMPTY_CELL_VALUE;
        private void resetButtonActionPerformed(java.awt.event.ActionEvent evt) {                                           
            /* reset all the variable to original state */
            setDiskAmount = 0;
            setAnimationDelay = 0;
            setPhysicalDelay = 0;
            moveNumber = 0;
            movesLeft = 0;
            intMovesLeft = 0;
            buttonPressed = false;
            windowState = 0;
            this.startButton.setEnabled(true);
            this.diskAmount.setEditable(true);
            this.animationDelay.setEditable(true);
            this.physicalDelay.setEditable(true);
            /* reset all the cell vales to empty (this could be its own function) */
            for (int row = ROW - 1;row >= 0; row--) {
                for (int col = 0;col < COLUMNS ; col++) {
                    diskCells[row][col] = EMPTY_CELL_VALUE;
            /* reset the content of the TextFields and Area */
            this.diskAmount.setText("");
            this.animationDelay.setText("");
            this.physicalDelay.setText("");
            this.outTextArea.setText("");
            /* repaint the display panel */
            this.hanoiPanel.repaint();
        /* i have no idea why this is here...It was generated by Netbeans when I
         *made the reset button.  As you can see it made 2.  The one above it the same
         *except it contains code.  Since it was automatically generated
         *I cannot delete it.
        private void resetButtonMouseReleased(java.awt.event.MouseEvent evt) {                                         
        /* is executed when the start button is pressed.
         *also executes a field check and intializes key variables. Finally,
         *it executes the solution and generates the solve time
        private void startButtonMouseReleased(java.awt.event.MouseEvent evt) {                                         
            /* check if the program has already been run (without being reset) */
            if (!buttonPressed){
                /* check the fields to ensure the input is correct and useable */
                if (checkFields()){
                    /* give button a pressed status if all info valid */
                    buttonPressed = true;
                    windowState = 1;
                    /* disable the button */
                    this.startButton.setEnabled(false);
                    /* disable the fields */
                    this.diskAmount.setEditable(false);
                    this.animationDelay.setEditable(false);
                    this.physicalDelay.setEditable(false);
                    /* setup the disks on the starting pole */
                    setup();
                    /* initialize the number of moves required. 2 to the power of n minus 1 */
                    movesLeft = Math.pow(2, setDiskAmount) - 1;
                    /* convert the number to an integer */
                    intMovesLeft = (int)movesLeft;
                    /* set the physical delay */
                    setPhysicalDelay = Integer.parseInt(this.physicalDelay.getText());
                    /* create and start a new thread.  This is EXTREMELY important
                     *as it allows for GUI to be repainted while the soulution
                     *is animated */
                    SolveEngine s = new SolveEngine();
                    s.start();               
         * @param args the command line arguments
        public static void main(String args[]) {
            java.awt.EventQueue.invokeLater(new Runnable() {
                public void run() {
                    new HanoiFrame().setVisible(true);
        /*returns the Animation panel area graphics
         *@return Animation area graphics
        public static Graphics getAnimationArea(){
            /* get the usable area of poleA */
            Container clientArea = hanoiPanel;
            //Container clientArea = this.getContentPane();
            /* get the graphics to the display panel*/
            Graphics gfx = clientArea.getGraphics();
            return gfx;
         *set up the requested amount of disks on the first pole
         *@param diskAmount the amount of disks entered by the user
        public void setup(){
            int numberOfDisks = setDiskAmount;
            this.disks = new Disk[numberOfDisks];
            int diskNumber = 0;
            int diskWidth = POLE_AREA_WIDTH - 4;
            int arcH = DISK_ARC_HEIGHT;
            int arcW = DISK_ARC_WIDTH;
            int x = startX;
            int y = startY;
            int row = 0;
            int col = 0;
            /* get the graphics to the display panel*/
            //Graphics gfx = getAnimationArea();
            /* set the color of the disks */
            //gfx.setColor(Color.MAGENTA);
            /* draw the specified number of disks */
            while (diskNumber < numberOfDisks){
                /* reduce the y position */
                y = startY - diskNumber * CELL_HEIGHT;
                /* draw the disk */
                //gfx.fillRoundRect(x, y, diskWidth, DISK_HEIGHT, arcH, arcW);
                /* create a new instance of disk */
                newDisk = new Disk(x, y, diskWidth);
                /* give the new disk an id */
                this.disks[diskNumber] = newDisk;
                /* add the id to the cell array of poleA */
                this.diskCells[row][col] = diskNumber;
                /* make the disk smaller and center */
                x = x + 8;
                diskWidth = diskWidth - 16;
                /* increase disk number */
                diskNumber++;
                /* move to the next row */
                row++;
            repaint();
         *move the disk from a source pole to the destination pole.
         *this should take the source col and destination col to determine where to draw the
         *disk.  It will also need to know to draw the disk in the first available cell
         *in a col
         *@param source the starting pole of the next move
         *@param destination the end pole of the next move
        public void moveDisk(int src, int dest){
            /* the lines below would not be necessary if I were to pass the Graphics
             *gfx object as a parameter.  I may have to use this option in order
             *to work around the current repainting issue */
            /* get the graphics to the display panel*/
            Graphics gfx = getAnimationArea();
            /* get the id of the disk to be moved */
            int disk = getDiskId(src);
            /* get the to and from rows */
            int sourceRow = getRow(src);
            int destinationRow = getRow(dest);
            /* set the co ordintates of the destination */
            int col = dest * POLE_AREA_WIDTH;
            int x = disks[disk].getStartX() + col;
            int y = startY - (destinationRow * CELL_HEIGHT);
            int width = disks[disk].getDiskWidth();
            disks[disk].setStartX(x);
            disks[disk].setStartY(y);
            disks[disk].setDiskWidth(width);
            //System.out.println("startX " + x);
            //System.out.println("startY " + y);
            //System.out.println("destination row " + destinationRow);
            //System.out.println("disk " + disk);
            //System.out.println("Width " + width);
            diskCells[sourceRow - 1][src] = EMPTY_CELL_VALUE;
            /* set the destination row to the disk id */
            diskCells[destinationRow][dest] = disk;
            drawDisk();
            repaint();
        public void drawDisk(){
            int diskNum = setDiskAmount -1;
            int i = 0;
            Graphics gfx = getAnimationArea();
            gfx.setColor(Color.MAGENTA);
            while(diskNum >= 0){
                //System.out.println("here is the disk IDs " + diskNum);
                //System.out.println("the startY during draw " + disks[diskNum].getStartY());
                gfx.fillRoundRect(disks[diskNum].getStartX(), disks[diskNum].getStartY(), disks[diskNum].getDiskWidth(), DISK_HEIGHT, DISK_ARC_WIDTH, DISK_ARC_HEIGHT);
                diskNum--;
        public void paint(Graphics gfx){
            if(windowState == 0){
                super.paint(gfx);
                setup();
            } else if (windowState == 1){
                super.paint(gfx);
                drawDisk();
         *returns the id of the disk
         *@param col the the designated column
         *@return the disk identification number
        public static int getDiskId(int col){
            int diskIdent = 0;
            /* initialize the row number to max -1, because the array start at 0 */
            int row = MAX_DISKS - 1;
            /* do a cell check while row is greater than 0
             *this is done so that is starts at the top row
             *and moves down
            while (row > EMPTY_CELL_VALUE){
                /* when the first cell that is not -1 is reached get the disk number
                 *that disk will be the smallest in the stack */
                if(diskCells[row][col] != -1){
                    //diskIdent = this.diskCells[row][col];
                    diskIdent =diskCells[row][col];
                    break;
                row--;
            return diskIdent;
         *returns the first available row
         *@param col the designated col
         *@return the first available row number
        public static int getRow(int col){
            int rowNumber = 0;
            /* cycle through the cells until it finds an empty one */
            while (diskCells[rowNumber][col] != -1){
                rowNumber++;
            return rowNumber;
         *calculate the total time it takes for the tower of hanoi game to be
         *solved, given the amount of disk and the amount of time it takes
         *to physically move a disk from one pole to the other.
        public static void totalTime(){
            int timeInSeconds = setPhysicalDelay * intMovesLeft;
            int i = 0;
            int seconds = 0;
            int minute = 0;
            int hour = 0;
            int day = 0;
            int month = 0;
            int year = 0;
            while (i < timeInSeconds){
                if(seconds > 60){
                    minute++;
                    seconds = 0;
                if(minute > 60){
                    hour++;
                    minute = 0;
                if(hour > 24){
                    day++;
                    hour = 0;
                if(day > 30){
                    month++;
                    day = 0;
                if(month > 12){
                    year++;
                    month = 0;
                seconds++;
                i++;
            updateMessageCenter("It would take:" + year + " years " + month + " months " + day +
                    " days " + hour + " hours " + minute + " minutes and " + seconds + " seconds, to move " + setDiskAmount +
                    " disks at " + setPhysicalDelay + " seconds per move");
       

    Sorry if my post was a little too cryptic...
    "How do you know? You have a problem you can't solve. Anything could be your issue." Agreed. However, using the process of elimination and debug statments I have been able to narrow the scope of the issue.
    "If you can't solve it by executing the code and adding debug statements how to you expect us to help."If I could solve but "executing code and adding debug statements" there would be no need to post the problem here.
    "We don't know exactly what you are attempting to do."Trying to paint my graphics to a JPanel based on a set of co ordinates.
    "We don't know why you are passing the Graphics object around."Why not? is it impossible to do it this way?
    "The big problem is in the alogorithm you use to determine the location of each component."Who said you couldn't read minds?
    "If you are using some kind of animation then I would use a Timer to schedule the moving of components. I don't even see how you are doing this in your code."Sorry I guess stating that I didn't post my entire code may have threw things off...I do use a timer in a seperate class. I will include it in the next post.
    "I can't tell if you are using Threads of not."guess you overlooked these lines of code:
                    /* create and start a new thread.  This is EXTREMELY important
                     *as it allows for GUI to be repainted while the soulution
                     *is animated */
                    SolveEngine s = new SolveEngine();
                    s.start();   Here is the code once again:
    public class HanoiFrame extends javax.swing.JFrame {
        private static final int STATE_SETUP = 0;
        private static final int STATE_ANIMATE = 1;
        private static final int POLE_AREA_HEIGHT = 356;
        private static final int POLE_AREA_WIDTH = 205;
        private static final int DISK_ARC_HEIGHT = 15;
        private static final int DISK_ARC_WIDTH = 15;
        private static final int DISK_HEIGHT = 23;
        private static final int MAX_DISKS = 10;
        private static final int MAX_ANIMATION_DELAY = 30000;
        private static final int MAX_PHYSICAL_DELAY = 100000;
        private static final int MIN_DISKS = 1;
        private static final int MIN_ANIMATION_DELAY = 1;
        private static final int MIN_PHYSICAL_DELAY = 1;
        private static final int EMPTY_CELL_VALUE = -1;
        private static final int CELL_HEIGHT = 25;
        private static final int COLUMNS = 3;
        private static final int ROW = 11;
        private  static final int MILLISECONDS_PER_SECOND = 1000;
        private final static String newline = "\n";
        private static Disk[] disks;
        private static Disk newDisk;
        private static int[][] diskCells;
        public static  int startX = 2;
        public static  int startY = 340;
        public static int setDiskAmount = 0;
        public static int setAnimationDelay = 0;
        public static int  setPhysicalDelay = 0;
        public static int  moveNumber = 0;
        public static int intMovesLeft = 0;
        private boolean  buttonPressed = false;
        private double movesLeft = 0;
        private int windowState = 0;
        /** Creates new form HanoiFrame */
        public HanoiFrame() {
            initComponents();
            /* initialize the "poles" to hold a certain number of "cells */
            this.diskCells = new int[ROW][COLUMNS];
            for (int row = ROW - 1;row >= 0; row--) {
                for (int col = 0;col < COLUMNS ; col++) {
                    diskCells[row][col] = EMPTY_CELL_VALUE;
        private void resetButtonActionPerformed(java.awt.event.ActionEvent evt) {                                           
            /* reset all the variable to original state */
            setDiskAmount = 0;
            setAnimationDelay = 0;
            setPhysicalDelay = 0;
            moveNumber = 0;
            movesLeft = 0;
            intMovesLeft = 0;
            buttonPressed = false;
            windowState = 0;
            this.startButton.setEnabled(true);
            this.diskAmount.setEditable(true);
            this.animationDelay.setEditable(true);
            this.physicalDelay.setEditable(true);
            /* reset all the cell vales to empty (this could be its own function) */
            for (int row = ROW - 1;row >= 0; row--) {
                for (int col = 0;col < COLUMNS ; col++) {
                    diskCells[row][col] = EMPTY_CELL_VALUE;
            /* reset the content of the TextFields and Area */
            this.diskAmount.setText("");
            this.animationDelay.setText("");
            this.physicalDelay.setText("");
            this.outTextArea.setText("");
            /* repaint the display panel */
            this.hanoiPanel.repaint();
        /* i have no idea why this is here...It was generated by Netbeans when I
         *made the reset button.  As you can see it made 2.  The one above it the same
         *except it contains code.  Since it was automatically generated
         *I cannot delete it.
        private void resetButtonMouseReleased(java.awt.event.MouseEvent evt) {                                         
        /* is executed when the start button is pressed.
         *also executes a field check and intializes key variables. Finally,
         *it executes the solution and generates the solve time
        private void startButtonMouseReleased(java.awt.event.MouseEvent evt) {                                         
            /* check if the program has already been run (without being reset) */
            if (!buttonPressed){
                /* check the fields to ensure the input is correct and useable */
                if (checkFields()){
                    /* give button a pressed status if all info valid */
                    buttonPressed = true;
                    windowState = 1;
                    /* disable the button */
                    this.startButton.setEnabled(false);
                    /* disable the fields */
                    this.diskAmount.setEditable(false);
                    this.animationDelay.setEditable(false);
                    this.physicalDelay.setEditable(false);
                    /* setup the disks on the starting pole */
                    setup();
                    /* initialize the number of moves required. 2 to the power of n minus 1 */
                    movesLeft = Math.pow(2, setDiskAmount) - 1;
                    /* convert the number to an integer */
                    intMovesLeft = (int)movesLeft;
                    /* set the physical delay */
                    setPhysicalDelay = Integer.parseInt(this.physicalDelay.getText());
                    /* create and start a new thread.  This is EXTREMELY important
                     *as it allows for GUI to be repainted while the soulution
                     *is animated */
                    SolveEngine s = new SolveEngine();
                    s.start();
         *Check all the fields at once to ensure that they are valid
        private boolean checkFields(){
            String numberOfDisks = null;
            String animationDelay = null;
            String physicalDelay = null;
            numberOfDisks = this.diskAmount.getText();
            animationDelay = this.animationDelay.getText();
            physicalDelay = this.physicalDelay.getText();
            /* initiate my array of error messages */
            ArrayList errMsg = new ArrayList(0);
            /* check if the number of disks was left blank */
            if (numberOfDisks.equals("")){
                errMsg.add("Please enter the Number of Disks (MAX " + MAX_DISKS + ")");
            }else{
                /* check if the input given is valid */
                try {
                    /* parse the disk amount entered into an integer */
                    setDiskAmount = Integer.parseInt(numberOfDisks);
                    /* check the # of disks entered is greater than 0 and less than 10 */
                    if (setDiskAmount < MIN_DISKS){
                        errMsg.add("Number of Disks must be greater than " + MIN_DISKS);
                    } else if (setDiskAmount > MAX_DISKS){
                        errMsg.add("Number of Disks must be less than" + MAX_DISKS);
                } catch (NumberFormatException ex) {
                    errMsg.add("Number of Disks must be a Number");
            /* check if animation delay was left blank */
            if (animationDelay.equals("")){
                errMsg.add("Please enter disk Animation Delay");
            } else {
                /* check if the input given is valid */
                try {
                    /* parse the animation delay entered into an integer */
                    setAnimationDelay = Integer.parseInt(animationDelay);
                    /* check range of animation delay */
                    if (setAnimationDelay < MIN_ANIMATION_DELAY){
                        errMsg.add("Animation Delay must be greater than 0");
                    } else if (setAnimationDelay > MAX_ANIMATION_DELAY){
                        errMsg.add("Animation Delay must be less than " + MAX_ANIMATION_DELAY);
                } catch (NumberFormatException ex) {
                    errMsg.add("Animation Delay must be a Number");
            /* check if physical delay was left blank */
            if (physicalDelay.equals("")){
                errMsg.add("Please enter the Physical disk delay");
            } else {
                /* check if the input given is valid */
                try {
                    /* parse the physical delay entered into an integer */
                    setPhysicalDelay = Integer.parseInt(physicalDelay);
                    /* check check the range of the physical delay */
                    if (setPhysicalDelay < MIN_PHYSICAL_DELAY){
                        errMsg.add("Physical Delay must be greater than 0");
                    } else if (setPhysicalDelay > MAX_PHYSICAL_DELAY){
                        errMsg.add("Physical Delay must be less than " + MAX_PHYSICAL_DELAY);
                } catch (NumberFormatException ex) {
                    errMsg.add("Physical Delay must be a Number");
            /* if there is any problem, add the message to the popup and display */
            if (!errMsg.isEmpty()){
                JOptionPane.showMessageDialog(this, errMsg.toArray());
                return false;
            return true;
         * @param args the command line arguments
        public static void main(String args[]) {
            java.awt.EventQueue.invokeLater(new Runnable() {
                public void run() {
                    new HanoiFrame().setVisible(true);
        /*returns the Animation panel area graphics
         *@return Animation area graphics
        public static Graphics getAnimationArea(){
            /* get the usable area of poleA */
            Container clientArea = hanoiPanel;
            //Container clientArea = this.getContentPane();
            /* get the graphics to the display panel*/
            Graphics gfx = clientArea.getGraphics();
            return gfx;
         *set up the requested amount of disks on the first pole
         *@param diskAmount the amount of disks entered by the user
        public void setup(){
            int numberOfDisks = setDiskAmount;
            this.disks = new Disk[numberOfDisks];
            int diskNumber = 0;
            int diskWidth = POLE_AREA_WIDTH - 4;
            int arcH = DISK_ARC_HEIGHT;
            int arcW = DISK_ARC_WIDTH;
            int x = startX;
            int y = startY;
            int row = 0;
            int col = 0;
            /* get the graphics to the display panel*/
            //Graphics gfx = getAnimationArea();
            /* set the color of the disks */
            //gfx.setColor(Color.MAGENTA);
            /* draw the specified number of disks */
            while (diskNumber < numberOfDisks){
                /* reduce the y position */
                y = startY - diskNumber * CELL_HEIGHT;
                /* draw the disk */
                //gfx.fillRoundRect(x, y, diskWidth, DISK_HEIGHT, arcH, arcW);
                /* create a new instance of disk */
                newDisk = new Disk(x, y, diskWidth);
                /* give the new disk an id */
                this.disks[diskNumber] = newDisk;
                /* add the id to the cell array of poleA */
                this.diskCells[row][col] = diskNumber;
                /* make the disk smaller and center */
                x = x + 8;
                diskWidth = diskWidth - 16;
                /* increase disk number */
                diskNumber++;
                /* move to the next row */
                row++;
            repaint();
         *move the disk from a source pole to the destination pole.
         *this should take the source col and destination col to determine where to draw the
         *disk.  It will also need to know to draw the disk in the first available cell
         *in a col
         *@param source the starting pole of the next move
         *@param destination the end pole of the next move
        public void moveDisk(int src, int dest){
            /* the lines below would not be necessary if I were to pass the Graphics
             *gfx object as a parameter.  I may have to use this option in order
             *to work around the current repainting issue */
            /* get the graphics to the display panel*/
            Graphics gfx = getAnimationArea();
            /* get the id of the disk to be moved */
            int disk = getDiskId(src);
            /* get the to and from rows */
            int sourceRow = getRow(src);
            int destinationRow = getRow(dest);
            /* set the co ordintates of the destination */
            int col = dest * POLE_AREA_WIDTH;
            int x = disks[disk].getStartX() + col;
            int y = startY - (destinationRow * CELL_HEIGHT);
            int width = disks[disk].getDiskWidth();
            disks[disk].setStartX(x);
            disks[disk].setStartY(y);
            disks[disk].setDiskWidth(width);
            //System.out.println("startX " + x);
            //System.out.println("startY " + y);
            //System.out.println("destination row " + destinationRow);
            //System.out.println("disk " + disk);
            //System.out.println("Width " + width);
            diskCells[sourceRow - 1][src] = EMPTY_CELL_VALUE;
            /* set the destination row to the disk id */
            diskCells[destinationRow][dest] = disk;
            drawDisk();
            repaint();
            String output = "";
            //must initialize row to max - 1 and increment 'til = 0
            //since the array position starts at 0
            //this will print the array from the top down
            for (int row = ROW - 1;row >= 0; row--) {
                for (int colm = 0;colm < COLUMNS ; colm++) {
                    output = output + diskCells[row][colm];
                output = output + "\n";
            System.out.println(output);
            System.out.println(newline);
        public void drawDisk(){
            int diskNum = setDiskAmount -1;
            int i = 0;
            Graphics gfx = getAnimationArea();
            gfx.setColor(Color.MAGENTA);
            while(diskNum >= 0){
                //System.out.println("here is the disk IDs " + diskNum);
                //System.out.println("the startY during draw " + disks[diskNum].getStartY());
                gfx.fillRoundRect(disks[diskNum].getStartX(), disks[diskNum].getStartY(), disks[diskNum].getDiskWidth(), DISK_HEIGHT, DISK_ARC_WIDTH, DISK_ARC_HEIGHT);
                diskNum--;
        public void paint(Graphics gfx){
            if(windowState == 0){
                super.paint(gfx);
                setup();
            } else if (windowState == 1){
                super.paint(gfx);
                drawDisk();
         *returns the id of the disk
         *@param col the the designated column
         *@return the disk identification number
        public static int getDiskId(int col){
            int diskIdent = 0;
            /* initialize the row number to max -1, because the array start at 0 */
            int row = MAX_DISKS - 1;
            /* do a cell check while row is greater than 0
             *this is done so that is starts at the top row
             *and moves down
            while (row > EMPTY_CELL_VALUE){
                /* when the first cell that is not -1 is reached get the disk number
                 *that disk will be the smallest in the stack */
                if(diskCells[row][col] != -1){
                    //diskIdent = this.diskCells[row][col];
                    diskIdent =diskCells[row][col];
                    break;
                row--;
            return diskIdent;
         *returns the first available row
         *@param col the designated col
         *@return the first available row number
        public static int getRow(int col){
            int rowNumber = 0;
            /* cycle through the cells until it finds an empty one */
            while (diskCells[rowNumber][col] != -1){
                rowNumber++;
            return rowNumber;
         *calculate the total time it takes for the tower of hanoi game to be
         *solved, given the amount of disk and the amount of time it takes
         *to physically move a disk from one pole to the other.
        public static void totalTime(){
            int timeInSeconds = setPhysicalDelay * intMovesLeft;
            int i = 0;
            int seconds = 0;
            int minute = 0;
            int hour = 0;
            int day = 0;
            int month = 0;
            int year = 0;
            while (i < timeInSeconds){
                if(seconds > 60){
                    minute++;
                    seconds = 0;
                if(minute > 60){
                    hour++;
                    minute = 0;
                if(hour > 24){
                    day++;
                    hour = 0;
                if(day > 30){
                    month++;
                    day = 0;
                if(month > 12){
                    year++;
                    month = 0;
                seconds++;
                i++;
            updateMessageCenter("It would take:" + year + " years " + month + " months " + day +
                    " days " + hour + " hours " + minute + " minutes and " + seconds + " seconds, to move " + setDiskAmount +
                    " disks at " + setPhysicalDelay + " seconds per move");
         *add the message to the diplay window
         *currently this is not necessary, but may be required to
         *dynamically display the contents of message into the text area
         *@param message the message to be added/appended the the text area
        public static void updateMessageCenter(String message){
            /* append text to the message */
            outTextArea.append(message + newline);
            /* ensure the the most recent line is viewable - auto scroll */
            outTextArea.setCaretPosition(outTextArea.getDocument().getLength());
        public class SolveEngine extends Thread {
            /** Creates a new instance of SolveEngine */
            public SolveEngine() {
            public void run(){
                /* start the engine/animation */
                solutionEngine(HanoiFrame.setDiskAmount,0, 2, 1);
                /* calculate and print the total time after the solution is complete */
                HanoiFrame.totalTime();
         *the recursive solution to the Towers of Hanoi problem
         *@param diskAmount the number of disks that need to be moved
         *@param start the identity of the starting column
         *@param end the identity of the ending column
         *@param temp the identity of the temporary column
            public void solutionEngine(int diskAmount,int start, int end, int temp){
                int disks = diskAmount;
                int startPole = start;
                int endPole = end;
                int tempPole = temp;
                try {
                    if ( disks == 1 ) {
                        HanoiFrame.moveNumber++;
                        HanoiFrame.updateMessageCenter("Moving disk from  "+ startPole + " to "+ endPole + " Move #: " + HanoiFrame.moveNumber + " of " + HanoiFrame.intMovesLeft);
                        /* delay the movement of the disk */
                        Thread.sleep(HanoiFrame.setAnimationDelay);
                        /* move the disk */
                        moveDisk(startPole, endPole);
                    } else {
                        solutionEngine( disks - 1, startPole, tempPole, endPole);
                        HanoiFrame.moveNumber++;
                        HanoiFrame.updateMessageCenter("Moving disk from  "+ startPole + " to "+ endPole + " Move #: " + HanoiFrame.moveNumber + " of " + HanoiFrame.intMovesLeft);
                        /* delay the movement of the disk */
                        Thread.sleep(HanoiFrame.setAnimationDelay);
                        moveDisk(startPole, endPole);
                        solutionEngine( disks - 1, tempPole, endPole, startPole);
                } catch (InterruptedException ex) {
                    ex.printStackTrace();
        }

  • 10.4.5 - mac mini can't connect to network via airport since upgrade

    I've been experiencing problems since upgrading to 10.4.3. Mainly, I've noticed that I can't easily connect to our wireless home network all the time. The pattern has been that I start by shutting down my computer completely. When I start up it again, it can't connect to the network. I have to create a new profile and then it will connect. That was buggy, but at least I found a hack. However, since upgrading to 10.4.5, I can't connect to our home network at all. The Internet Connect application says that I am connected to the base station, however I can't connect to the outside world via a shell, browser or email application. Our network is secured with a WEP and the base station is a D-Link. I searched the forums for some tips, but didn't find anything. Pointers appreciated.

    Be very careful about the sequence you do it. You must make sure that the airport connection is turned off (i.e. the airport menu icon looks more like a profiled eyeball without the iris than a series of lines like the towers of hanoi). Then create a new location in the Airport network preference, and make sure that these settings are there under Options
    1. Keep looking for recent networks
    2. Automatically add new networks to the preferred network list.
    3. Change the status of Enable interference robustness.
    And by default, join preferred networks in the Airport location.

  • What do you call this basic technique?

    Request: Is there a name for the technique I'm using below, because I
    know I've seen it and done it before.
    Context: I'd like to allow the user to resize images, while preserving
    their width:height aspect ratio. My GUI has a pair of JSpinners, for width
    and height, and when one is adjusted, the other should change.
    Example: if the aspect ratio is 2:1, setting the width spinner to 201
    should cause the height spinner to change to 100 (I truncate), whilst setting
    the height spinner to 100 should cause the width spinner to change to 200.
    But: I don't want those reactions to cascade: from the example, if the
    user sets the width spinner to 201, the height spinner should change to 100,
    but that is where it should stop -- the width spinner shouldn't itself react
    and change to 200.
    My solution: I'm a fan of fixing it in the model, and here is my tweak for
    SpinnerNumberModel: public class SafeSpinnerNumberModel extends SpinnerNumberModel {
         public SafeSpinnerNumberModel(int value, int minimum, int maximum, int stepSize) {
             super(value, minimum, maximum, stepSize);
         public void setValue(Object value) {
             if (!inSetValue) {
                 inSetValue = true;
                 super.setValue(value);
                 inSetValue = false;
         private boolean inSetValue;
    In my code, there are two JSpinners (with SafeSpinnerNumberModels),
    and each model has a ChangeListener that reacts by adjusting the other model.
    The flag stops the potential feedback loop.
    So, again, what would you call this technique?
    Thanks,
    BDLH

    Me too. And they love all those visual little
    thingies so much: ooh, when
    the number is positive it's displayed in black,
    otherwise it's red. I'm a
    genius! No lemme put 90 percent profit in here, just
    for the "what-if"
    question part. Yay! It's black!You should see some of the spreadhseets we have here. Risk management, process compliance, earned value management... I have no idea what any of this is, but its all thousands of rows of red-green-yellow, telling who's not doing any work. And if you change one value all the colors change all over the place. I bet they have Tetris encoded in there.
    I attempted to finish my bookkeeping for Q3 last
    Sunday but I was
    distracted by myself attempting to do the Towers of
    Hanoi puzzle
    using Excel. I managed to make it work, but it was so
    awful (using
    additional cells etc) I deleted it all. I still have
    to finish up Q3 ...Hmm, I believe I'll start short-selling JosAH Industries ;-)

  • Tween in custom class

    I'm a relative flash/actionscript newbie. I created a towers
    of hanoi solution moving movie clips around using Tweens. This all
    worked great when the action script containing the Tween creation
    existed on what I guess is the root movie clip (within the Action
    script window of my .fla file).
    I tried moving the hanoi solution into a custom class
    (extending EventDispatcher) and now the tween does not 'run'. I've
    stepped through my code with the debugger and added plenty of trace
    statements and am pretty sure all the arguments to the Tween
    constructor are correct.
    _currentTween = new Tween(_movingDiskMc, "_y",
    Regular.easeOut, _movingDiskMc._y, _yMin, _duration);
    Is there something fundamental I'm missing? Is the frame rate
    an issue with the custom class? The value of _duration above is 5.
    thx
    - Kurt

    ahhhh.... after further review found that my
    'onMotionFinished' event handlers were being called but in the
    debugger the scope is the Tween class not my Hanoi class. That's
    messed up
    found the discussion in the help topic regarding scope of
    event handlers and using the 'suggested strategy' things are
    working fine now

  • JTextArea not showing

    I can get my first set of JScrollPane and JTextArea to appear, but the second just will not. Here is all my code refering to the frame. I hope you can find what I cannot.
            public Frame(){
                Object[] items={"Choose One","1","2","3","4","5","6","7","8","9","10"};
                JPanel c=(JPanel)getContentPane();
                JOptionPane jOpt=new JOptionPane();
                ImageIcon icon=new ImageIcon();
                jArea=new JTextArea();
                JScrollPane jScroll=new JScrollPane(jArea);
                jArea2=new JTextArea();
                JScrollPane jScroll2=new JScrollPane(jArea2);
                setDefaultCloseOperation(EXIT_ON_CLOSE);
                setSize(new Dimension(250, 500));
                setTitle("Towers Of Hanoi");
                //setResizable(false);
                setLocationRelativeTo(null);
                jScroll.setPreferredSize(new Dimension(125, 500));
                jScroll.setPreferredSize(new Dimension(125,500));
                jScroll.setViewportView(jArea);
                jScroll2.setViewportView(jArea2);
                c.setLayout(new BorderLayout());
                c.add(jOpt);
                jOpt.setVisible(false);
                c.add(jScroll, java.awt.BorderLayout.WEST);
                c.add(jScroll2, java.awt.BorderLayout.EAST);
                jScroll2.setVisible(true);
                boolean done=false;
                String s="";
                while(done==false){
                    s=(String)jOpt.showInputDialog(this,"How many disks should be used?","",jOpt.PLAIN_MESSAGE,icon,items,"Choose One");
                    if(!s.equals("Choose One"))
                        done=true;
                height=Integer.parseInt(s);
                show();
            }//Close Frame Constructor

    maybe
    setLocationRelativeTo(null);
    jScroll.setPreferredSize(new Dimension(125, 500));
    jScroll.setPreferredSize(new Dimension(125,500));//should be jScroll2.setPreferredSize(...)
    jScroll.setViewportView(jArea);

  • Help me   a TowersOfHanoi problem

    // Lab 3: TowersOfHanoi.java
    // Program solves the Towers of Hanoi problem
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    public class TowersOfHanoi extends JApplet implements ActionListener {
    JLabel label;
    JTextField input;
    JTextArea outputArea;
    String output;
    public void init()
    output = "";
    // create components
    label = new JLabel( "Enter number of disks ( 1-9 ): " );
    input = new JTextField( 5 );
    input.addActionListener( this );
    outputArea = new JTextArea( 15, 20 );
    /* Write code that creates a JScrollPane and attach outputArea to it */
    // outputArea.setText( output );
    JScrollPane scroll = new JScrollPane(outputArea);
    // add components to applet
    Container container = getContentPane();
    container.setLayout( new FlowLayout() );
    /* Write code to add the components to the content pane */
    input.addActionListener(this);
    container.add(label);
    container.add(input);
    container.add(scroll);
    // recusively move disks through towers
    /* write header for method tower */
    String tower(int n,String peg1,String peg2,String peg3)
    /* Write code here that tests for the base case (i.e., one disk).
    In this case, move the last disk from peg 1 to peg 3 and return. */
    if(n==1)
    return output+="\n"+peg1+"--->"+peg3;
    // move ( disks - 1 ) disks from peg1 to peg2 recursively
    /* Write a recursive call to method tower that moves
    ( disks - 1 ) disks from peg1 to peg2 */
    else
    tower(n-1,peg1,peg3,peg2);
    // move last disk from peg1 to peg3 recursively
    output += "\n" + peg1 + " --> " + peg3;
    // move ( disks - 1 ) disks from peg2 to peg3 recursively
    /* Write a recursive call to method tower that moves
    ( disks - 1 ) disks from peg2 to peg3 */
    tower(n-1,peg2,peg1,peg3);
    return output;
    // actually sort the number of discs specified by user
    public void actionPerformed( ActionEvent e )
    output = "";
    /* call method tower and pass it the number input by the user,
    a starting peg of 1, an ending peg of 3 and a temporary peg of 2 */
    int n=Integer.parseInt(input.getText());
    String peg1="1";
    String peg2="2";
    String peg3="3";
    output+=tower(n,peg1,peg2,peg3);
    outputArea.setText( output );
    } // end class TowersOfHanoi
    when n=3 , its answer : &#65297;&#65293;&#65293;&#65310;&#65299;&#65307;&#65297;&#65293;&#65293;&#65310;&#65298;&#65307;&#65299;&#65293;&#65293;&#65310;&#65298;&#65307;&#65297;&#65293;&#65293;&#65310;&#65299;&#65307;&#65298;&#65293;&#65293;&#65310;&#65297;&#65307;&#65298;&#65293;&#65310;&#65299;&#65307;&#65297;&#65293;&#65293;&#65310;&#65299;
    I really don't understand it , Who can explain the operation course of this procedure ? thank you so much!!!

    when n=3, the result is 1-->3 , 1-->2, 3-->2,1-->3,
    2-->1, 2-->3, 1-->3. I don't
    understand 1-->2, 3-->2.It means move the top disk of peg 1 to be on top of
    all the disks on peg 2, then move the top disk on peg
    3 to be on top of all disks on peg 3.Two, sir.
    Signed,
    Brother Maynard.

  • 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

  • Stck-overflow(recursion)

    Hi, am vikranth, joied just now.
    I'm getting "stack-overflow-error" whenever I use recursion, for example, to solve towers of hanoi problem.
    Please tell me how can I get along with it?

    Thank you friends..for clearing my doubt.
    The program is working;
    but println statements are showing errors, in the following code.
    // method to move N stones from "from" to "to",
    Hanoi.java
    // eventually using temp as a temporary place:
    public class Hanoi
    public static void main(String[] args)
    Recur r = new Recur();
    r.move(3,1,2,3);
    class Recur
    public void move( int N,int from,int to,int temp) // N must be > 0
    if(N > 0)
    move(N-1, from, temp, to);
    println("from "+from+" to "+temp);
    //moveOne(A, B); // move 1 element from A to B
    move(N-1, temp, to, from);
    println("from "+temp+" to "+to);
    May I know why?

Maybe you are looking for

  • Connection Problem with Oracle and Tomcat.

    I was able to enter Oracle using scott/tiger when I did not connect Tomcat.But when I connect tomcat I am unable to log onto Oracle. When I logged to the database then I tried to start the Tomcat but it gave an exception.So I went to the task manager

  • Solaris 9: LMS 3.2 SP1 (LMS 3.2.1) and CSCtn45425

    Solaris 9: LMS 3.2 SP1 (LMS 3.2.1) and CSCtn45425 the point patch for CSCtj01051 breaks Apache on Solaris 9 because libm.so.2 cannot be found (it exists on solaris 10 not solaris 9). In the ReadMe of LMS 3.2 SP1 it states that CSCtj01051 is solved. B

  • Sales doc archiving

    Hi I am trying to archive SD and MM docs for previous years using SARA. However, when I run the pre-processor job for sales docs, the spool shows me some docs can not be archived because they have in-progress status or subsequent docs are not complet

  • My screen

    dear apple Sorry for my English, I do not speak English well But I will try to explain the problem as much as possible i have iphone 3gs 32gb serial number 86017FPU3NR after i update it to ios 5 There was a problem in the screen Screen has become a p

  • ISR ADOBE Workflow Scenario - Data doesn't update the Backend

    Hi, I am currently working on ISR-LOA Scenario. I have made all the ISR-Form-Process configurations and linked with my workflow. I event tested my process in the backend and portal. The process goes end to end. But does not update the infotyptes. No