User:Eriksiers/Permute a string: Difference between revisions

From Rosetta Code
Content added Content deleted
m (added a note)
m (VB note)
Line 3: Line 3:
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 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 [[BASIC]]s too, but I haven't checked.
Note also that the sub works almost unchanged in [[Visual Basic]] (if you change the output method, e.g. <code>'''PRINT'''</code>-><code>'''PRINT #'''</code>) and [[PowerBASIC]]. Probably other [[BASIC]]s too, but I haven't checked.


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

Revision as of 21:14, 31 August 2019

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 almost unchanged in Visual Basic (if you change the output method, e.g. PRINT->PRINT #) 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>