THINK FIRST·CODE LATER

← All labs

Towers of Hanoi

Problem

Move n disks from peg A to peg C, using B, never placing a larger disk on a smaller one. The recursive idea: move n − 1 disks out of the way (A → B), move the largest disk (A → C), move the n − 1 disks back on top (B → C).

Write Hanoi with solve(int n, char from, char to, char via) that counts moves in a static field and prints the first limit moves (1. disk 1 A -> C), and long countMoves(int n) computed recursively from M(n) = 2·M(n − 1) + 1. main reads n and limit and prints:

1. disk 1 A -> C
2. disk 2 A -> B
3. disk 1 C -> B
... (4 more moves)
Total moves: 7, formula: 7
63 disks: 9223372036854775807 moves = Long.MAX_VALUE? true

Data for this lab

Your program reads its data from standard input. Download the file, then give it to your program as shown below. Start with data set 1: its expected output is given.

l17-4-data-1.txt

3 3
What your program must print for l17-4-data-1.txt
1. disk 1 A -> C
2. disk 2 A -> B
3. disk 1 C -> B
... (4 more moves)
Total moves: 7, formula: 7
63 disks: 9223372036854775807 moves = Long.MAX_VALUE? true

Run your program first, then open this and compare line by line: your output must contain these lines exactly.

How to give the file to my program

Terminal (macOS, Linux, or Windows Command Prompt), after compiling:

java Main < l17-4-data-1.txt

Windows PowerShell does not understand <:

Get-Content l17-4-data-1.txt | java Main

IntelliJ IDEA: Run → Edit Configurations → Redirect input from. Or simply paste the content of the file into the console when the program waits for input.

Write it here or in your IDE, then paste it. Compile and test it yourself before comparing. Your code stays in your browser — it is never sent to or stored on the server.