Programming and Problem Solving with Java

(やまだぃちぅ) #1

(^646) | Recursion
doTowers(circleCount – 1, beginPeg, endPeg, auxPeg);
outFile.println("Move circle from peg "+ beginPeg



  • " to peg "+ endPeg);
    // Move n – 1 circles from auxiliary peg to ending peg
    doTowers(circleCount – 1, auxPeg, beginPeg, endPeg);
    }
    }
    It’s difficult to believe that such a simple algorithm actually works, but we can prove it.
    We enclose the method within a driver class that invokes the doTowersmethod. Output state-
    ments have been added so that we can see the values of the arguments with each recursive
    call. Because two recursive calls are made within the method, we have indicated which re-
    cursive statement issued the call.
    // Driver class for doTowers method
    // Reads the number of circles from a file and calls doTowers
    importjava.io.*; // File types
    public classTowers
    {
    public static voidmain(String[] args) throwsIOException
    {
    // Prepare files
    PrintWriter outFile; // Output data file
    BufferedReader inFile; // Input data file
    inFile = new BufferedReader(new InputStreamReader(System.in));
    outFile = new PrintWriter(new FileWriter("recursion.out "));
    int circleCount; // Number of circles on starting peg
    System.out.println("Input the number of circles: ");
    circleCount = Integer.parseInt(inFile.readLine());
    outFile.println("Input number of circles: "+ circleCount);
    outFile.println("OUTPUT WITH "+ circleCount + " CIRCLES");
    outFile.print("From original: ");
    doTowers(circleCount, 1, 2, 3);
    infile.close();
    outFile.close();
    }

Free download pdf