Generate all permutations
Posted: Mon Apr 06, 2009 6:33 pm
Works also with PB 5.20
A permutation, also called an "arrangement number" or "order," is a rearrangement of the elements of an ordered list.
Generating all permutations of a list is not a simple task. I cannot remember whether I didn't manage to write a general algorithm for it at all, or wether it was way to slow. Anyhow, I decided to look with what someone with "a little more"
knowledge than me had come up, and implemented it in PureBasic. Enjoy!
A permutation, also called an "arrangement number" or "order," is a rearrangement of the elements of an ordered list.
Generating all permutations of a list is not a simple task. I cannot remember whether I didn't manage to write a general algorithm for it at all, or wether it was way to slow. Anyhow, I decided to look with what someone with "a little more"

Code: Select all
EnableExplicit
Procedure Visit (Array a(1))
; This is just a sample Procedure.
Protected i, text$
text$ = ""
For i = 1 To ArraySize(a())
text$ + Str(a(i)) + " "
Next
Debug text$
EndProcedure
Procedure Algorithm_L (Array a(1))
; after Donald E. Knuth:
; The Art Of Computer Programming, Vol. 4, Fascicle 2 (2005)
; Algorithm 7.2.1.2 L (pp. 39 f.)
; Lexicographic permutations;
; also works when equal elements are present, meaning a() is a multiset.
; Implemented in PureBasic 4.30 by Little John
Protected h, i, k, n
n = ArraySize(a())
Repeat
;-- Step 1: Visit
Visit(a())
;-- Step 2: Find h
h = n - 1
While a(h) >= a(h+1)
h - 1
Wend
If h = 0
ProcedureReturn
EndIf
;-- Step 3: Increase a(h)
k = n
While a(h) >= a(k)
k - 1
Wend
Swap a(h), a(k)
;-- Step 4: Reverse a(h+1..n)
i = h + 1
k = n
While i < k
Swap a(i), a(k)
i + 1
k - 1
Wend
ForEver
EndProcedure
;-- Demo
Define i, n
n = 6 ; Caution, choosing a big n will take long time!
Dim a(n)
For i = 1 To n
a(i) = i
Next
Algorithm_L(a())