Non-Recursive Generation of all permutation (knuth)

Source: Internet
Author: User
'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)

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.