作业帮 > 综合 > 作业

求一fortran程序,取出n个连续自然数的所有n级排列.

来源:学生作业帮 编辑:大师作文网作业帮 分类:综合作业 时间:2024/11/10 22:36:55
求一fortran程序,取出n个连续自然数的所有n级排列.
例如 n=4的:要存到文件里面的是所有1234的排列:1234,1243,1324,1342,····4321 这样共n!=24个排列的数据.
要求n可以取任意正整数.
求一fortran程序,取出n个连续自然数的所有n级排列.
program main
character(20) arr(20000),str
Integer n,ss(20),k,m
n = 4
k = 0
m = JC(n)
Do While (k < m)
str = ""
Call GetNum(str, n) !获得随机数
!判断随机数是否已经出现过
 ii = 1
do i = 1 , k
If (trim(arr(i))==trim(str)) Then
ii = 0
cycle
End If
enddo
!如果随机数未出现过则储存在arr中
If (ii == 1) Then
k = k + 1
arr(k) = str
!输出结果 也可输出到文件中
write(*,*) trim(str)
End If
end do
End program
Subroutine GetNum(str, n)
!获得一个n位随机数,该随机数内各位数字都不重复
character(20) str
 character(1) s1
Integer ss(20),n,a,b
 real x
str = ""
ss=0
i = 0
Do While (Len(trim(str)) < n)
 call random(x)
a = Int(x * n + 1)
b = 1
do j = 1, i
If (a == ss(j)) Then
b = 0
cycle
End If
end do
If (b == 1) Then
i = i + 1
ss(i) = a
write(s1,'(i1)') a
str = trim(str) // s1
End If
end do
End Subroutine
integer Function JC(n)
!计算n的阶乘
integer n
JC = 1
do i = 1 , n
JC = JC * i
end do
End Function
我的源代码是vba的,结果可以直接输出在excel中,花了好久改成fortran.vba的也一起给你吧:
Private Sub nj()
Dim arr(10000) As String, n As Integer, str As String, ss(10) As Integer
Sheet1.Cells.Clear
n = 5
k = 0
m = JC(n)
Do While k < m
str = ""
Call GetNum(str, n)
ii = 1
For i = 1 To k
If arr(i) = str Then
ii = 0
Exit For
End If
Next
If ii = 1 Then
k = k + 1
arr(k) = str
Cells(k, 1) = str
End If
DoEvents
Loop
MsgBox ""
End Sub
Private Sub GetNum(str, n)
Dim ss() As Integer
str = ""
ReDim ss(n)
i = 0
Do While Len(str) < n
a = Int(Rnd * n + 1)
b = 1
For j = 1 To i
If a = ss(j) Then
b = 0
Exit For
End If
Next
If b = 1 Then
i = i + 1
ss(i) = a
str = str & ss(i)
'MsgBox ss(i) & "," & str
End If
DoEvents
Loop
End Sub
Private Function JC(n)
JC = 1
For i = 1 To n
JC = JC * i
Next
End Function
再问: 暂时没时间细看,但是 ··· 随机数? 我也想过用随机方法把所有不重复的都试出来? 运算量是不大了点?
再答: 速度很快的,你运行一下试试就知道。
下面有一个人分享的算法没用随机数,但计算量貌似惊人了。参考一下吧(里面也有我的回答):
http://zhidao.baidu.com/question/872680146775499292.html?oldq=1