Permutation generating algorithm

Full BASIC is not good at list processing. Wealternate list processing with string processing.
The following external subprogram prints a permutation of the characters contained in s$ followed by t$.

200 EXTERNAL SUB Permutate(s$,t$)
210 IF t$="" THEN
220    PRINT s$
230 ELSE 
240    FOR i=1 TO LEN(t$)
250       LET x$=s$ & t$(i:i)
260       LET y$=t$(1:i-1) & t$(i+1:LEN(t$)) 
270       CALL Permutate(x$,y$)
280    NEXT i
290 END IF
300 END SUB

For example, When you run CALL Permutate("12", "345") , you get

12345
12354
12435
12453
12534
12543

When t$ is an empty string, s$ itself is a permutation that should be output (210, 220 lines ).
When t$ is not empty,in lines 250 and 260, pull one letter from t$ and get x$ by connecting it with s$, and get y$ by pulling the letter from t$,and the call Permutate(x$,y$) (250~270行).
Apply this process to each letter of t$ (240~280 lines ).

When you want to get a list of permutations, call eternal sub-program Permutate passing an empty string to the first argument and letters for permutaion to the soecond argument. This program prints all permutains.
Example.

100 DECLARE EXTERNAL SUB Permutate
110 CALL Permutate("", "12345")
120 END
200 EXTERNAL SUB Permutate(s$,t$)
210 IF t$="" THEN
220    PRINT s$
230 ELSE 
240    FOR i=1 TO LEN(t$)
250       LET x$=s$ & t$(i:i)
260       LET y$=t$(1:i-1) & t$(i+1:LEN(t$)) 
270       CALL Permutate(x$,y$)
280    NEXT i
290 END IF
300 END SUB

Getting all permutaions in an array

When you want the list of all permutaions, pass a string array additionally to get them.

100 DECLARE EXTERNAL SUB perm
110 LET s$="123"
120 DIM p$(FACT(LEN(s$)))
130 LET k=0
140 CALL perm("", "123",p$,k)
150 FOR i=1 TO k
160    PRINT p$(i)
170 NEXT i
180 END
200 EXTERNAL SUB perm(s$,t$,p$(),k)
210 IF t$="" THEN
215    LET k=k+1
220    LET p$(k)=s$
230 ELSE 
240    FOR i=1 TO LEN(t$)
250       LET x$=s$ & t$(i:i)
260       LET y$=t$(1:i-1) & t$(i+1:LEN(t$)) 
270       CALL perm(x$,y$,p$,k)
280    NEXT i
290 END IF
300 END SUB

At the 160-line portion, you can perform processing corresponding to each permutation.


戻る