Welcome to MSDN Blogs Sign in | Join | Help

Permutations

I saw this post which shows some VFP code to permute a string. For example, there are 6 permutations of “abc”:

            abc, acb, bac, bca, cab, cba

 

There are n! permutations of a string of length n.

 

 

I dug up some old code that did the same thing in fewer lines.

 

 

nn=0

permute("abcd",0)

 

PROCEDURE permute(cstr,nLev)

      LOCAL nTrylen,i

      nTrylen= LEN(cstr)-nLev

      IF nTryLen = 0

            nn=nn+1

            ?nn,cstr

      ELSE

            FOR i = 1 to nTrylen

                  IF i>1      && swap nlev+1 and nlev+i chars

                        cstr= LEFT(cstr,nlev) + SUBSTR(cstr,nLev+i,1) +;

                              SUBSTR(cstr,nLev+2, i-2)+SUBSTR(cstr,nlev+1,1)+SUBSTR(cstr,nLev+i+1)

                  ENDIF

                  permute(cstr,nlev+1)

            ENDFOR

      ENDIF

RETURN

 

 

 

 

48662

 

Published Tuesday, January 18, 2005 12:12 PM by Calvin_Hsia
Filed under:

Comment Notification

If you would like to receive an email when updates are made to this post, please register here

Subscribe to this post's comments using RSS

Comments

# re: Permutations

Friday, January 28, 2005 3:37 PM by Robert Hoogstraat
Here is another possible solution with little code:

* PERMUTATIONS
*
* def'n:
* If M = (n)P(r) = P(n):(r) denotes the number of
* permutations of (n) distinct things taken (r) at a time,
* -- M = n(n-1)(n-2)...(n-r+1) = n!/(n-r)!

Permutations( "12345" )

PROCEDURE Permutations ;
( ;
tvThings AS CHARACTER, ;
tvStatic AS CHARACTER, ;
tvN AS INTEGER ;
) AS VOID
LOCAL iX AS INTEGER
IF VARTYPE(tvStatic)="L"
* First time procedure called, preset missing parameters.
CLEAR
PUBLIC lnPermutation AS INTEGER
lnPermutation = 0
tvStatic = ""
tvN = LEN(tvThings)
ENDIF
FOR iX = 1 TO tvN
IF tvN > 2
Permutations( RIGHT( tvThings, tvN-1 ), tvStatic+LEFT(tvThings,1), tvN-1 )
ELSE
lnPermutation = lnPermutation + 1
? lnPermutation, tvStatic+tvThings
ENDIF
tvThings = SUBSTR(tvThings,2) + LEFT(tvThings,1)
ENDFOR
ENDPROC

# Good site

Wednesday, January 23, 2008 8:20 PM by Vilyamdn

<a href= http://index1.morun5.com >boy scout camp forestburg</a>

Leave a Comment

(required) 
required 
(required) 

  
Enter Code Here: Required
 
Page view tracker