Download as pdf or txt
Download as pdf or txt
You are on page 1of 3

Fortran Code written by Dr. Abhijit Kar Gupta, kg.abhi@gmail.

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

!Disks are numbered from top

C
nn=mod(n,2)
if(nn.eq.0)then
C
C
C

The number is even


------------------

10

call exch(na,nb,n)

! Exchange betwen A and B

Fortran Code written by Dr. Abhijit Kar Gupta, kg.abhi@gmail.com


call chk(nc,n,nsum)
if(nsum.eq.ntot)go to 30
C
call exch(na,nc,n)
! Exchange betwen A and C
call chk(nc,n,nsum)
if(nsum.eq.ntot)go to 30
C
call exch(nb,nc,n)
call chk(nc,n,nsum)
if(nsum.eq.ntot)then
go to 30
else
go to 10
endif

! Exchange betwen B and C

C
else
C
C
C
20

The number is Odd


----------------call exch(na,nc,n)
! Exchange betwen A and C
call chk(nc,n,nsum)
if(nsum.eq.ntot)go to 30

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

! Exchange betwen C and B

C
endif
C
C
C
30
C

Final position on Slot C


-----------------------write(*,*)(nc(i),i=1,n)
stop
end

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

Fortran Code written by Dr. Abhijit Kar Gupta, kg.abhi@gmail.com


ny(j)=nx(i)
nx(i)=0
return
endif
enddo
if(ny(n).eq.0)then
ny(n)=nx(i)
nx(i)=0
return
endif
endif
enddo
do i=1,n
if(ny(i).ne.0.and.ny(i-1).eq.0)then
!Move from y
do j=1,n-1
if(nx(j).eq.0.and.nx(j+1).gt.ny(i))then !Move to x
nx(j)=ny(i)
ny(i)=0
return
endif
enddo
if(nx(n).eq.0)then
nx(n)=ny(i)
ny(i)=0
return
endif
endif
enddo
return
end
C
C
C

SUBROUTINE
==========
subroutine chk(nz,n,nsum)
dimension nz(10)
nsum=0
do i=1,n
nsum=nsum+nz(i)
enddo
return
end

You might also like