'Knuth's Algorithm
'Generate all permutation
Option explicit
Dim result, counter
Const N = 4
Const format = 10
Sub swap (byref inarray, first, second)
Dim t
T = inarray (first)
Inarray (first) = inarray (second)
Inarray (second) = T
End sub
Function genper (byref counter, N, Format)
Dim C (10), O (10), T (10)
Dim I, j, S, Q, result
Dim oloopflag, iloopflag
For I = 0 to n-1
C (I) = 0
O (I) = 1
T (I) = I
Next
Oloopflag = true
Counter = 0
While oloopflag
For I = 0 to n-1
Result = Result & T (I)
Next
Result = Result &""
Counter = counter + 1
If counter mod format = 0 then
Result = Result & CHR (13) & CHR (10)
End if
J = n-1
S = 0
Iloopflag = true
While iloopflag
Q = C (j) + O (j)
If q> J or q <0 then
If j = 1 then
Iloopflag = false
Oloopflag = false
Else
If q> J then
S = S + 1
End if
O (j) =-O (j)
J = J-1
End if
Else
Swap T, J-C (j) + S, J-q + S
C (j) = Q
Iloopflag = false
End if
Wend
Wend
Genper = Result
End Function
Result = genper (counter, N, Format)
Result = Result & CHR (13) & CHR (10) & "Total:" & Counter
Msgbox (result)