Thursday 3 October 2013

Tower Of Hanoi Iterative : Java : BlueJ

Objective :


The Tower of Hanoi (also called the Tower of Brahma or Lucas' Tower, and sometimes pluralised) is a mathematical game or puzzle. It consists of three rods, and a number of disks of different sizes which can slide onto any rod. The puzzle starts with the disks in a neat stack in ascending order of size on one rod, the smallest at the top, thus making a conical shape.
  • Only one disk may be moved at a time.
  • Each move consists of taking the upper disk from one of the rods and sliding it onto another rod, on top of the other disks that may already be present on that rod.
  • No disk may be placed on top of a smaller disk.



The objective of the puzzle is to move the entire stack to another rod, obeying the following rules:
With three disks, the puzzle can be solved in seven moves.


BlueJ Program Screenshot :



Java Program Source Code :

/**
 * The class TowerOfHanoiIterative computes smallest number 
 * of moves using iteration and without any stack.
 * @author  SHANTANU KHAN 
 * @version 1.0.0
 */
import java.util.*;
public class TowerOfHanoiIterative
{
    private int nDisks; // INSTANCE VARIABLE
    
    public TowerOfHanoiIterative(int nDisks){ // CONSTRUCTOR
        this.nDisks=nDisks;
    }
    
    public void execute(){
        int n=nDisks; // NUMBER OF DISKS
        int limit = (int)Math.pow(2,n)-1; // NUMBER OF ITERATIONS = 2^n - 1
        for(int i=0;i<limit;i++){
            int disk = disk(i); // DISK TO BE MOVED
            int source = ( movements(i,disk)*direction(disk,n))%3; // SOURCE PEG
            int destination = (source + direction(disk,n))%3; // DESTINATION PEG
            move(disk,source,destination);
        }      
    }
    private int disk(int i) { // RETURNS THE DISK TO BE MOVED IN i
        int C, x= i+1; // SINCE FOR STARTS WITH 0, ADDING 1
        for(C=0;x%2==0;C++){ // CONTINUOUS DIVISION BY 2 UNTIL ODD OCCURS
            x/=2;
        }
        return C; // RETURNS THE COUNTER C
    }
    private int movements(int i, int d) { // HOW MANY TIMES DISK d HAS MOVED BEFORE STAGE i
        while(d--!=0)
            i/=2;
        return (i+1)/2;
    }
    private int direction(int d,int n) { // EACH DISK MOVES IN SAME DIRECTION CW=1, ACW=2
        return 2 - (n + d)%2;
    }
    private void move(int disk, int source, int destination) {
        System.out.println("Move Disk " + (disk+1)+ " from Tower " + (source+1) + " to Tower " + (destination+1));
    }
    
    public static void main(String[] args){
       Scanner sc=new Scanner(System.in);
       System.out.print("Enter the No. of Disks : ");
       TowerOfHanoiIterative toh=new TowerOfHanoiIterative(sc.nextInt());
       toh.execute();
    }
}

No comments:

Post a Comment