Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Permute
#6
Works well, I think.

perm "abcd" 0 4

result:
abcd
abdc
acbd
acdb
adcb
adbc
bacd
badc
bcad
bcda
bdca
bdac
cbad
cbda
cabd
cadb
cdab
cdba
dbca
dbac
dcba
dcab
dacb
dabc

Here is my version (permute), very similar but stores result into variable instead of printing.

Code:
Copy      Help
function $s str&sout [n] [l] ;;n is 0-based position of first char, l string length

;EXAMPLE
;str s
;permute("abcd" s)
;out s



if(l<1) l=len(s)

int i c

if n>=l
,;No characters to permute . . print string.
,sout.formata("%s[]" s)
else
,;Work through all characters of string.
,for i n l
,,;Swap this character with the first one.
,,c = s[i]; s[i] = s[n]; s[n] = c
,,;Permute remainder of string.
,,permute(s sout n+1 l)
,,;Swap back again.
,,c = s[i]; s[i] = s[n]; s[n] = c


Messages In This Thread

Forum Jump:


Users browsing this thread: 3 Guest(s)