Professional Documents
Culture Documents
Tower of Hanoi: Fortran Code
Tower of Hanoi: Fortran Code
com
Tower of Hanoi:
In this mathematical puzzle there are
three rods. In the first rod (we call A),
there are some disks of different sizes
stacked in the manner that the sizes
decrease upward. There are two other
empty rods (we call B, the next one and
C, the right most one). Now the task is
to move the entire set of disks and stack
on the third rod to look exactly the same in the way that (i) only one
disk (from the top) can be moved, (ii) no disk can be placed over a
smaller disk.
Pic Source: Wikipedia.
Algorithm:
If the number of disks is Even:
# The movements are in the following order
Between A & B
Between A & C
Between B & C
Repeat the steps until all the disks are in C.
If the number of disks is Odd:
# The movements are in the following order
Between A & C
Between A & B
Between B & C
Repeat the steps until all the disks are in C.
FORTRAN 77 CODE
C
C
TOWER OF HANOI
-------------dimension na(10),nb(10),nc(10)
C
Write(*,*)'Give the number of disks'
read(*,*)n
C
ntot=0
do i=0,n
na(i)=i
nb(i)=0
nc(i)=0
ntot=ntot+i
enddo
C
nn=mod(n,2)
if(nn.eq.0)then
C
C
C
10
call exch(na,nb,n)
C
else
C
C
C
20
C
call exch(na,nb,n)
! Exchange betwen A and B
call chk(nc,n,nsum)
if(nsum.eq.ntot)go to 30
C
call exch(nc,nb,n)
call chk(nc,n,nsum)
if(nsum.eq.ntot)then
go to 30
else
go to 20
endif
C
endif
C
C
C
30
C
C
C
SUBROUTINE
==========
subroutine exch(nx,ny,n)
dimension nx(10),ny(10)
do i=1,n
if(nx(i).ne.0.and.nx(i-1).eq.0)then
!Move from x
do j=1,n-1
if(ny(j).eq.0.and.ny(j+1).gt.nx(i))then !Move to y
SUBROUTINE
==========
subroutine chk(nz,n,nsum)
dimension nz(10)
nsum=0
do i=1,n
nsum=nsum+nz(i)
enddo
return
end