A typical recursive implementation of a solver for the Towers of Hanoi puzzle pu
ID: 3644109 • Letter: A
Question
A typical recursive implementation of a solver for the Towers of Hanoi puzzlepublic class TowersOfHanoi
{
public static void main(String[] args)
{
// Example for four discs
move(4, "A", "B", "C");
}
// move n discs from
Explanation / Answer
/** * TowersOfHanoi.java * Created by Stijn Strickx on Aug. 12 2006 * Copyright 2006 Stijn Strickx, All rights reserved */ import java.io.*; public class TowersOfHanoi { static int moves = 0; static int totalDisks = 0; public static void main(String[] arguments) throws java.io.IOException { int disks; char fromPole = 'A'; char withPole = 'B'; char toPole = 'C'; disks = getNumber(" How many disks are there on the tower? "); totalDisks = disks; if(totalDisks > 10){ System.out.println("Working..."); } FileOutputStream fos = new FileOutputStream("TowersOfHanoiSolution.txt"); PrintStream ps = new PrintStream(fos); solveHanoi(disks, fromPole, toPole, withPole, ps); ps.close(); System.out.println(); System.out.println(" Amount of moves: " + moves + " "); System.out.print("You can now access the TowersOfHanoiSolution.txt file"); System.out.println(" which is in the same directory as the .class file of this program."); } static void solveHanoi(int disks, char fromPole, char toPole, char withPole, PrintStream ps) { if (disks >= 1) { solveHanoi(disks-1, fromPole, withPole, toPole, ps); moveDisk(fromPole, toPole, ps); solveHanoi(disks-1, withPole, toPole, fromPole, ps); } } static void moveDisk(char fromPole, char toPole, PrintStream ps) { moves++; if(totalDisksRelated Questions
Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.