Friday, March 7, 2014

TOWER OF HANOI USING APPLET in JAVA

                                                    TOWER OF HANOI  is very common program all over the world it is taught by the institutes as a very basic program. there are 'n' number of plates which are placed over a pig(stick) such a way smaller over the bigger one. We have to move the all disks to third pig (receiver pig ) using the temperary pig (mid pig) from the first pig (container pig) .
.There are two rules to do.
1.smaller disk over bigger only
2.only one disk moves at a time

There are three steps to do this problem.
     1.store the movement of disks using the below function called hanoi in a 2-D array. count is a counter.

'n' is the storing array.
    
     public  void hanoi(int m,char a,char b,char c)
{

if(m>0)
{
hanoi(m-1,a,c,b);
n[count][0]=a;
n[count][1]=c;
count++;
hanoi(m-1,b,a,c);
}
}
     
     now we got the position of all the disks in each step. 
     
     2.create the stable structure using applet . Stable structures are pig and the base
     call the paint function to paint all this pigs(sticks) and plates.
    to do this we take three 1-D arrays like  a[20],b[20],c[20] . initial we put n,n-1,n-2,.....1 numbers       in 'a' array.
    then we move these numbers using the storing array 'n' by the below function.
   
  public void run() {

for(int i=0;i<count;i++)
{
repaint();

if(n[i][0]=='a'&&n[i][1]=='b')
{
a[1][p2++]=a[0][p1];
p1--;
}
else if(n[i][0]=='a'&&n[i][1]=='c')
{

a[2][p3++]=a[0][p1];
p1--;
}
else if(n[i][0]=='b'&&n[i][1]=='c')
{

p2--;
a[2][p3++]=a[1][p2];

}
else if(n[i][0]=='b'&&n[i][1]=='a')
{
p1++;
p2--;
a[0][p1]=a[1][p2];

}
else if(n[i][0]=='c'&&n[i][1]=='a')
{
p3--;p1++;
a[0][p1]=a[2][p3];

}
else if(n[i][0]=='c'&&n[i][1]=='b')
{
p3--;
a[1][p2++]=a[2][p3];

}
try
{
Thread.sleep(100);
}
catch(InterruptedException ex)
{
}

}
}  
        
        3. Create a paint function such a way that pigs and base should remain as it is and disk should be created acording the number in perticular array.
ex. initially all the disks are at pig-1 so all disks should appear at 1st position. all the numbers are in 'a' array.


 public  void paint(Graphics g)
{
ctr++;
setBackground(Color.yellow);
g.setColor(Color.green);
g.fillRect(380, 500, 800,20);
for(int i=0;i<3;i++)
g.fillRect(500+245*i, 100, 10, 400);
g.setColor(Color.blue);
Font myFont = new Font("Serif", Font.BOLD, 22);
g.setFont( myFont);
g.drawString("time"+ctr, 380, 20);
 
  g.setColor(Color.black);
  for(int j=0;j<=p1;j++)
  g.fillRect(500-(a[0][j]*10), 500-21*(j+1), 20*a[0][j], 20);
  
  for(int j=0;j<p2;j++)
  g.fillRect(750-(a[1][j]*10), 500-21*(j+1), 20*a[1][j], 20);
  
  for(int j=0;j<p3;j++)
  g.fillRect(1000-(a[2][j]*10), 500-21*(j+1), 20*a[2][j], 20);
  

   }



No comments:

Post a Comment

Contributors

Translate