在 Fortran 中创建任意数量的嵌套循环有哪些方法?例如,可以在运行时确定嵌套循环的数量 k:
do i1 = 1,n1
do i2 = 1,n2
do i3 = 1,n3
do i4 = 1,n4
...
! use i1,i2,i3,i4,....,ik for something
...
enddo
enddo
enddo
enddo
因此,如果我理解正确的话,您需要进行嵌套循环(通常希望将嵌套循环保持在最低限度)。
但是在编译时,你甚至不知道需要做多少个嵌套。
如果我遇到这个问题,我可能会将巢展开到一个循环中,并从头开始计算各种索引。这是我刚刚尝试过的一个例子:
program nested
implicit none
integer :: num_nests, i
integer, dimension(:), allocatable :: nest_limits
integer, dimension(:), allocatable :: nests
print *, "Please enter number of nests:"
read(*, *) num_nests
allocate(nest_limits(num_nests))
allocate(nests(num_nests))
print *, "Please enter nest limits:"
read(*, *) nest_limits
nests(:) = 1
outer_loop : do
print *, nests(:)
i = 1
! Calculate the next indices:
inner_loop : do
nests(i) = nests(i) + 1
! If this is still a valid index, exit the inner
! loop and go for the next iteration
if (nests(i) <= nest_limits(i)) exit inner_loop
! The index has overflown, so reset it to 1 and
! move to next index.
nests(i) = 1
i = i + 1
! If the next index would be outside of num_nests,
! the whole loop is finished.
if (i > num_nests) exit outer_loop
end do inner_loop
end do outer_loop
end program nested
chw21提供的方法有效。然而,我很快就遇到了深层嵌套循环的问题。工作量变得太重了,无法处理。幸运的是,就我而言,只有不同的指数才令人感兴趣。此外,顺序并不重要,即索引 5、3、2 将产生与 2、3、5 相同的结果。基本上,问题退化为提供彩票上的所有组合。如果您的问题属于这种性质,下面的代码可能会引起您的兴趣。
program indices
implicit none
integer, dimension(:), allocatable :: ns
integer :: i,j,k,ni,np,nt,ntmp
integer*8 :: nc
print *, "Number of towns to visit"
read(*, *) np
allocate(ns(np))
print *, "Total number of towns"
read(*, *) nt
if (nt<=0) then
print*,' Error: Please provide a positive value'
stop
endif
if(nt<np) then
print*,' Error: Number of towns to visit must be less'
print*,' than or eqaul to total number of towns.'
stop
endif
! Initialize .....
do i=1,np
ns(i)=i
enddo
ntmp=nt-np
nc=0
! ................
print*,' Combinations of towns to visit..:'
do
print*,ns(:)
! Do the appropriate work with ns here.
! .......
!
! Provide a new combination:
nc=nc+1
if (ns(np)<nt) then
ns(np)=ns(np)+1
elseif (ns(1)==(ntmp+1)) then
exit
else
do i=2,np
if(ns(i)==(ntmp+i)) then
ni=ns(i-1)
k=0
do j=i-1,np
k=k+1
ns(j)=ni+k
enddo
exit
endif
enddo
endif
enddo
print*,' Number of combinations..........:',nc
end program indices
也许,您可以将多重循环扁平化为单个循环,遍历所有所需的组合。 对于答案 1 的程序,可能如下所示:
程序嵌套 隐式无 整数 :: num_nests, i,j,k 整数、维度(:)、可分配::nest_limits 整数、维度(:)、可分配 :: 嵌套
print *, "Please enter number of nests:"
read(*, *) num_nests
allocate(nest_limits(num_nests))
allocate(nests(num_nests))
print *, "Please enter nest limits:"
read(*, *) nest_limits
do i=0,product(nest_limits)-1
j=i
do k=1,num_nests
nests(k)=1+mod(j,nest_limits(k))
j=j/nest_limits(k)
enddo
print *, nests(:)
enddo
结束程序嵌套