Permutations: Difference between revisions

Line 1,516:
3 1 2
3 2 1</pre>
 
== Alternate solution ==
 
Instead of looking up unused values, this program starts from [1, ..., n] and does only swaps, hence the array always represents a valid permutation.
The values need to be "swapped back" after the recursive call.
 
<lang fortran>program allperm
implicit none
integer :: n, i
integer, allocatable :: a(:)
read *, n
allocate(a(n))
a = [ (i, i = 1, n) ]
call perm(1)
deallocate(a)
contains
recursive subroutine perm(i)
integer :: i, j, t
if (i == n) then
print *, a
else
do j = i, n
t = a(i)
a(i) = a(j)
a(j) = t
call perm(i + 1)
t = a(i)
a(i) = a(j)
a(j) = t
end do
end if
end subroutine
end program</lang>
 
== Fortran 77 ==
Here is an alternate, iterative version in Fortran 77.
{{trans|Ada}}
Anonymous user