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