User:Eriksiers/Permute a string

From Rosetta Code
Revision as of 07:07, 9 January 2017 by Eriksiers (talk | contribs) (created)
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)

This is QBasic code to permute a string. I didn't put it in one of the permutations pages because I don't believe it does quite what those tasks require.

Note that this is heavily recursive, adding a level of recursion for each character in the string. Long strings will run out of stack space pretty fast.

<lang qbasic>DECLARE SUB Permute (unchanged$, volatile$)

'Permute() must be called with an empty string as the first arg, 'and the string to be permuted as the second. Permute "", "abc"

SUB Permute (unchanged$, volatile$)

   DIM L0 AS INTEGER
   IF LEN(volatile$) > 1 THEN
       FOR L0 = 1 TO LEN(volatile$)
           Permute unchanged$ + MID$(volatile$, L0, 1), LEFT$(volatile$, L0 - 1) + MID$(volatile$, L0 + 1)
       NEXT
   ELSE
       PRINT unchanged$; volatile$
   END IF

END SUB </lang>