Megosztás a következőn keresztül:


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

Comments

  • Anonymous
    January 28, 2005
    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
  • Anonymous
    January 23, 2008
    <a href= http://index1.morun5.com >boy scout camp forestburg</a>