1

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!

RADRaze2KX
  • 23
  • 5

2 Answers2

2
@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 
MC ND
  • 69,615
  • 8
  • 84
  • 126
  • This works incredibly well! I understand the loop, can you explain to me how the randomization works? How is it not repeating any of the words while still inside a loop? – RADRaze2KX Feb 27 '14 at 19:07
  • @user3361720, in both cases a little trick is used. Each word is preceded by a random number, in first case directly in the string output and in the second case in the index of the "array". Then in both cases, the list is ordered (and as the random number precedes the word, the final order is random) and then iterated and words concatenated. As each word is in it own line, no repeat can happen (unless repeated in input sentence, of course). – MC ND Feb 27 '14 at 19:29
1

Here's a simple method - it doesn't handle poison characters but for your string it's fine.

@echo off
call :scramble I really enjoy writing batch files
goto :EOF 
:scramble
set "scrambled%random%=%1"
shift
if not "%~1"=="" goto :scramble
for /f "tokens=1,* delims==" %%a in ('set scrambled') do set /p "=%%b "<nul
echo(
pause
foxidrive
  • 40,353
  • 10
  • 53
  • 68