I'm attempting to create a batch file that will take a pre-defined sentence and scramble it, then echo it to the user.
For example, predefined sentence: I really enjoy writing batch files
Echo to user: enjoy batch really files I writing
I understand how the %RANDOM% variable works, as well as looping, but because I don't know how long the sentence will be, nor understand how to define/populate arrays in batch files, I do not know where to begin.
Please help me fill in the missing pieces in my knowledge. Thank you!
@echo off
setlocal enableextensions enabledelayedexpansion
call :scramble "I really enjoy writing batch files" scrambled
echo %scrambled%
endlocal
exit /b
:scramble sentence returnVar
setlocal enabledelayedexpansion
set "output=" & for /f "tokens=2" %%y in ('cmd /q /v:on /c "for %%w in (%~1) do echo(^!random^! %%w"^|sort') do set "output=!output! %%y"
endlocal & set "%~2=%output:~1%"
exit /b
If instantiates a cmd that outputs each word preceded by a random number. This list is sorted, numbers removed and words concatenated. All this wrapped into a subroutine with input and output parameters.
For the usual approach used in other languages, splitting the string in parts, store into array (sort of, there are no arrays in batch scripting), shuffling and joining, the subroutine can be something like
:scramble sentence returnVar
setlocal enabledelayedexpansion
set "counter=0" & for %%w in (%~1) do ( set "_word[!random!_!counter!]=%%w" & set /a "counter+=1" )
set "output=" & for /f "tokens=2 delims==" %%w in ('set _word[') do set "output=!output! %%w"
endlocal & set "%~2=%output:~1%"
exit /b