permutations with repetition algorithm?

前端 未结 1 885
情歌与酒
情歌与酒 2020-12-22 09:57

I\'m trying to write a code in Fortran that generates that given the following input 1,2,3 generates the permutations with repetition:

111 112 113 121 122 123 . . .<

相关标签:
1条回答
  • 2020-12-22 10:30

    Here is one solution:

    module perm_mod
    contains
      subroutine print_permutations(A)
        implicit none
        integer,intent(in)    :: A(:)
        integer               :: i, j, l, remainder
        integer               :: idx(size(A,1)), stride(size(A,1))
    
        l = size(A,1)
    
        stride(1) = 1
        do i=2,l
          stride(i) = stride(i-1)*l
        enddo ! i
    
        do i=0,l**l-1
          remainder = i
          do j=l,1,-1
            idx(j) = remainder / stride(j)
            remainder = remainder - idx(j)*stride(j)
          enddo ! j
          print *,A(idx+1)
        enddo ! i
    
      end subroutine
    end module
    
    program perm
      use perm_mod
      implicit none
      integer,parameter :: A(3) = [ 1, 2, 3 ]
    
      call print_permutations(A)
    end program
    
    0 讨论(0)
提交回复
热议问题