教练,我想学FOR……FORTRAN

感谢Bloodblaze提供的一道简单的题目。以下是一个使用Fortran90进行DFS遍历的例子。具体题面稍后再说。

感谢Wikibooks和StackOverflow。如果没有他们,我是不可能在一夜之间入门Fortran的;-)

另外,我在网上找到了这些资源可供参考:

本以为总算可以可以早点去睡觉的,结果发现根本停不下来。这里就不得不提到编程过程中的一大错觉:

再写半个小时应该就能完工了。

我在1点的时候也是这么想的。

我可能是阿华田喝多了。

以及这里的代码高亮似乎并不支持Fortran……

PROGRAM test
IMPLICIT NONE

INTEGER, PARAMETER :: STUDENT_COUNT = 7
INTEGER, PARAMETER :: MAX_VACANCY = 3

INTEGER, DIMENSION(STUDENT_COUNT, MAX_VACANCY) :: VACANCY
INTEGER, DIMENSION(STUDENT_COUNT) :: schedule = 0
INTEGER :: solutionCount = 0

VACANCY = transpose(reshape( &
                 (/2,4,0, &
                   1,6,0, &
                   3,7,0, &
                   5,0,0, &
                   1,4,6, &
                   2,5,0, &
                   3,6,7/), &
                 (/MAX_VACANCY, STUDENT_COUNT/)))

!write(*,*) VACANCY(2,3)

CALL assignStudent(1)
WRITE(*,*) "Solutions: ", solutionCount

CONTAINS

RECURSIVE SUBROUTINE assignStudent(studentIndex)
    INTEGER, INTENT(IN) :: studentIndex
    INTEGER :: i, j, vc

    TEST_VACANCY: DO i = 1,MAX_VACANCY
        vc = VACANCY(studentIndex, i)
        IF (vc == 0) EXIT TEST_VACANCY
        ! sanity check
        DO j = 1,studentIndex - 1
            ! DOW is occupied
            IF (schedule(j) == vc) CYCLE TEST_VACANCY
        END DO
        ! so far, so good
        schedule(studentIndex) = vc
        IF (studentIndex >= STUDENT_COUNT) THEN
            ! the solution is complete
            DO j = 1, STUDENT_COUNT
                write(*,"(I4)",advance="no") schedule(j)
            END DO
            write(*,*)
            solutionCount = solutionCount + 1
            CYCLE TEST_VACANCY
        END IF
        ! the solution is not complete
        ! go to next level
        CALL assignStudent(studentIndex + 1)        
    END DO TEST_VACANCY
END SUBROUTINE assignStudent

END PROGRAM test

运行结果如下

root@localhost:/usr/local/fortran# gfortran test.f90
root@localhost:/usr/local/fortran# ./a.out
   4   1   3   5   6   2   7
   4   1   7   5   6   2   3
   4   6   3   5   1   2   7
   4   6   7   5   1   2   3
 Solutions:            4
root@localhost:/usr/local/fortran#

发表回复

您的电子邮箱地址不会被公开。 必填项已用 * 标注

ERROR: si-captcha.php plugin: GD image support not detected in PHP!

Contact your web host and ask them to enable GD image support for PHP.

ERROR: si-captcha.php plugin: imagepng function not detected in PHP!

Contact your web host and ask them to enable imagepng for PHP.

此站点使用Akismet来减少垃圾评论。了解我们如何处理您的评论数据

Content is available under CC BY-SA 3.0 unless otherwise noted.