Permutations: Difference between revisions

m (added whitespace before the TOC (table of contents), added a ;Task: (bold) header.)
Line 879:
---------------------------</pre>
=={{header|Batch File}}==
Recursive permutation generator.
Recursive permutation generator. Batch does'nt have local variables, so vars must be reset after a recursive call that modifies them. Swapping letters in a string is tricky too..
<lang Batch File>
:: Permutations in Batch
@echo off
setlocal enabledelayedexpansion
set arr=ABCD
set /a n=4
:: echo !arr!
call :permu %n% arr
goto:eof
 
:permu [%1]num &arr
setlocal
set /a num=%1-1
if %1 equ 1 call echo(!%2! & exit /b
for /L %%c in (1,1,%num%) do (
set /a "num=%1-1,n2=num-1"
::batch doe's nt have local vars so I reset num after the call
set arr=!%2!
if !num! gtr 1 call:permu !num! & set /a num=%1-1
for /L %%c in (10,1,%num%!n2!) do (
set /a n1="%1%%2"
call:permu !num! arr
if !n1! neq 0 (call :swapit %1 1 ) else (call :swapit %1 %%c)
set /a n1="%num&1%%2"
if !n1! neqequ 0 (call :swapit %1!num! 10 arr) else (call :swapit %1!num! %%c arr)
)
if !num! gtr 1 call:permu !num! arr
endlocal & set %2=%arr%
goto :eof
exit /b
 
:swapit [%1] [%2]from to &arr
setlocal
set /a from=%1-1,to=%2-1
set temp1arr=!arr:~%from%,13!
set temp2temp1=!arr:~%to%~1,1!
set temp2=!arr:~%~2,1!
set arr=!arr:%temp1%=@!
set arr=!arr:%temp2%=%temp1%!
set arr=!arr:@=%temp2%!
:: echo %1 %2 !%~3! !arr!
endlocal & set %3=%arr%
goto:eof
exit /b
</lang>
{{out}}