Gray code: Difference between revisions

m
→‎{{header|Batch File}}: less code, but slower (TnT)
(→‎{{header|Ursala}}: Added VBScript)
m (→‎{{header|Batch File}}: less code, but slower (TnT))
Line 549:
<lang dos>:: Gray Code Task from Rosetta Code
:: Batch File Implementation
 
@echo off
rem -------------- define batch file macros with parameters appended
Line 562:
rem note: if natnum is negative, then !outputvar! is empty
set tobinary=for %%# in (1 2) do if %%#==2 ( %\n%
for /f "tokens=1,2,3" %%a in ("!args!") do (set "natnum=%%a"^&set "bitlength=%%b"^&set "outputvar=%%c") %\n%
for /f "tokens=1,2,3" %%a in ("!args!") do (set "binarynatnum=%%a"^&set "bitlength=%%b"^&set "outputvar=%%c") %\n%
set "!outputvar!=" %\n%
if !natnum! geq 0 ( %\n%
Line 574 ⟶ 575:
) else set args=
 
goto :main-thing %== jump to the main thing ==%
rem gray code encoder up to bit #(!bitlength!-1)
rem -------------- usual "call" sections
rem argument: binary bitlength outputvar
rem the sad disadvantage of using these is that they are slow (TnT)
rem note: MSB is bit #0
set encoder=for %%# in (1 2) do if %%#==2 ( %\n%
for /f "tokens=1,2,3" %%a in ("!args!") do (set "binary=%%a"^&set "bitlength=%%b"^&set "outputvar=%%c") %\n%
if "!binary!" neq "" ( %\n%
set "!outputvar!=!binary:~0,1!" %\n%
set /a "lastidx=!bitlength!-1" %\n%
for /l %%m in (1,1,!lastidx!) do ( %\n%
set /a "previdx=%%m-1" %\n%
for %%x in (!previdx!) do set /a "newbit=!binary:~%%m,1!^^!binary:~%%x,1!" %\n%
for %%v in (!outputvar!) do set "!outputvar!=!%%v!!newbit!" %\n%
) %\n%
) %\n%
) else set args=
 
rem gray code decoder up to bit #(!bitlength!-1)encoder
rem argument: gray bitlengthnatnum outputvar
:encoder
rem note: MSB is bit #0
set /a "%~2=%~1^(%~1>>1)"
set decoder=for %%# in (1 2) do if %%#==2 ( %\n%
goto :eof
for /f "tokens=1,2,3" %%a in ("!args!") do (set "gray=%%a"^&set "bitlength=%%b"^&set "outputvar=%%c") %\n%
 
if "!gray!" neq "" ( %\n%
rem gray code decoder
set "!outputvar!=!gray:~0,1!" %\n%
rem argument: binary bitlengthnatnum outputvar
set /a "lastidx=!bitlength!-1" %\n%
:decoder
for /l %%m in (1,1,!lastidx!) do ( %\n%
set /a "previdxinp=%%m-~1" & set "%\n%~2=0"
:while-loop-1
for /f "tokens=1,2" %%x in ("!previdx! !outputvar!") do set /a "newbit=!gray:~%%m,1!^^!%%y:~%%x,1!" %\n%
if %inp% gtr 0 (
for %%v in (!outputvar!) do set "!outputvar!=!%%v!!newbit!" %\n%
set /a ) "%\n~2^=%inp%, inp>>=1"
goto while-loop-1
) %\n%
)
) else set args=
goto :eof
 
rem -------------- main thing
:main-thing
setlocal enabledelayedexpansion
echo(# -^> bin -^> enc -^> dec
for /l %%n in (0,1,31) do (
%tobinary% %%n 5 bin
%call :encoder% !bin! 5"%%n" "enc"
%decodertobinary% !enc! 5 decgray
echo(%%ncall -^> !bin! -^>:decoder "!enc!" -^> !"dec!"
%tobinary% !dec! 5 rebin
echo(%%n -^> !bin! -^> !gray! -^> !rebin!
)
exit /b 0</lang>
535

edits