Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

1 Background The Tower of Hanoi or Towers of Hanoi (also known as TheTowers of B

ID: 3614838 • Letter: 1

Question

1 Background

The Tower of Hanoi or Towers of Hanoi (also known as TheTowers of Brahma)

is a mathematical game or puzzle. It consists of threerods, and a number of disks of different sizes which can slide ontoany rod. The puzzle starts with the disks neatly stacked in orderof size on one rod, the smallest at the top, thus making a conicalshape. The objective of the puzzle is to move the entire stack toanother rod, obeying

sliding it onto another rod, on top of the otherdisks that may already be

present on that rod.

No disk may be placed on top of a smallerdisk.

2 Algorithm

Assume that we have three pegs, or rods, labeled A, B, andC. These labels may move at different steps. Numbern discs from 1 (smallest, topmost) ton (largest, bottommost).

To move n discs from peg A topeg C:

1. Move n -1 discsfrom A to B. This leaves disc n along on pegA.

2. Move disc n from A toC.

3. Move n -1 discsfrom B to C so they sit on disc n.

The above is a recursive algorithm: to carry out steps 1and 3, apply the same algorithm again for n-1. The entire procedure is a finite number of steps,since at some point the algorithm will be requiredfor n = 1. This step, moving a single disc from peg A to pegB, is trivial.

3 Requirements

Write a computer program that takesas input the starting peg, the destination peg, and the number ofdiscs to move. Your program should output every move necessaryas:

"Move disc 5 from peg A to peg C."(for example)

Explanation / Answer

please rate - thanks import java.util.*; public class hanoi { public static void main(String[] args) {int n; Scanner in=new Scanner(System.in); System.out.println("How many disks do you have? "); n=in.nextInt(); System.out.println("move move"); System.out.println("from to"); System.out.println(" peg peg"); hanoi(n,'A','B','C'); } public static void hanoi(int n, char from, char to , char use) {      if(n==1)        System.out.println(""+from+"     "+to);      else      {         hanoi(n-1,from,use,to);         hanoi(1,from,to,use);         hanoi(n-1,use,to,from);      } } }