User:Eriksiers/Permute a string

From Rosetta Code
Revision as of 08:53, 9 January 2017 by Eriksiers (talk | contribs) (added a note)

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.

Note also that the sub works unchanged in Visual Basic and PowerBASIC. Probably other BASICs too, but I haven't checked.

<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>