THINK FIRST·CODE LATER

← All labs

Towers of Hanoi without recursion

Problem

The recursive solution of the Towers of Hanoi is famous; here you solve the puzzle with three stacks and a loop. Disks 1 (smallest) to n start on peg A and must end on peg C.

The iterative rule: number the moves 1, 2, 3, …, 2ⁿ − 1 and, for an odd n,

  • move 1, 4, 7, … : the legal move between A and C;
  • move 2, 5, 8, … : the legal move between A and B;
  • move 3, 6, 9, … : the legal move between B and C.

For an even n, exchange the roles of B and C. Between two pegs exactly one move is legal: the smaller top disk goes onto the other peg (or onto the empty one).

Write HanoiStacks: read n; print every move when n ≤ 4; then always print the number of moves and the three pegs, top first. For the input

3

the program prints

Move 1: disk 1 from A to C
Move 2: disk 2 from A to B
Move 3: disk 1 from C to B
Move 4: disk 3 from A to C
Move 5: disk 1 from B to A
Move 6: disk 2 from B to C
Move 7: disk 1 from A to C
Moves: 7
Peg A (top first): []
Peg B (top first): []
Peg C (top first): [1, 2, 3]

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.

d4-8-data-1.txt

3
What your program must print for d4-8-data-1.txt
Move 1: disk 1 from A to C
Move 2: disk 2 from A to B
Move 3: disk 1 from C to B
Move 4: disk 3 from A to C
Move 5: disk 1 from B to A
Move 6: disk 2 from B to C
Move 7: disk 1 from A to C
Moves: 7
Peg A (top first): []
Peg B (top first): []
Peg C (top first): [1, 2, 3]

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 < d4-8-data-1.txt

Windows PowerShell does not understand <:

Get-Content d4-8-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.