Skip to content
Snippets Groups Projects
Commit 94fe0478 authored by Jonas Riedel's avatar Jonas Riedel
Browse files

Add new file

parent b7dbd0e3
Branches
No related tags found
No related merge requests found
PROGRAM TowersOfHanoi
USE STACKMOD
IMPLICIT NONE
INTEGER, PARAMETER :: num_discs = 3
TYPE(disc) :: discs(num_discs)
INTEGER :: i
! Initialize the stacks
TYPE(STACK) :: source_stack, auxiliary_stack, destination_stack
CALL INIT(source_stack)
CALL INIT(auxiliary_stack)
CALL INIT(destination_stack)
! Create discs and push them onto the source stack
DO i = num_discs, 1, -1
discs(i)%num = i
discs(i)%color = i
discs(i)%diam = 2 * i
CALL PUSH(source_stack, discs(i))
END DO
! Call the recursive subroutine to solve the Towers of Hanoi puzzle
WRITE(*, *) "Initial State:"
WRITE(source_stack)
WRITE(auxiliary_stack)
WRITE(destination_stack)
WRITE(*, *)
CALL SolveTowersOfHanoi(num_discs, source_stack, auxiliary_stack, destination_stack)
! Clean up memory
CALL DELETE(source_stack)
CALL DELETE(auxiliary_stack)
CALL DELETE(destination_stack)
END PROGRAM TowersOfHanoi
SUBROUTINE SolveTowersOfHanoi(n, source, auxiliary, destination)
USE STACKMOD
IMPLICIT NONE
INTEGER, INTENT(IN) :: n
TYPE(STACK), INTENT(INOUT) :: source, auxiliary, destination
TYPE(disc) :: disc
IF (n == 1) THEN
! Move the top disc from the source to the destination peg
CALL POP(source, disc)
CALL PUSH(destination, disc)
WRITE(*, *) "Move disc ", disc%num, " from peg ", CHAR(source), " to peg ", CHAR(destination)
WRITE(source)
WRITE(auxiliary)
WRITE(destination)
WRITE(*, *)
ELSE
! Recursive case:
! 1. Move (n-1) discs from source to auxiliary peg using destination peg as the auxiliary
CALL SolveTowersOfHanoi(n - 1, source, destination, auxiliary)
! 2. Move the nth disc from source to destination peg
CALL POP(source, disc)
CALL PUSH(destination, disc)
WRITE(*, *) "Move disc ", disc%num, " from peg ", CHAR(source), " to peg ", CHAR(destination)
WRITE(source)
WRITE(auxiliary)
WRITE(destination)
WRITE(*, *)
! 3. Move (n-1) discs from auxiliary peg to destination peg using source peg as the auxiliary
CALL SolveTowersOfHanoi(n - 1, auxiliary, source, destination)
END IF
END SUBROUTINE SolveTowersOfHanoi
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment