Reputation: 105
On windows command line, is it possible to re-arrange numbers at random?
For example, I have the following logic in a batch file, where it selects numbers from s at random. This is allowing repeat items. I would like to have the items non-repeating.
@echo off
set i=
set s=12345678
set m=0
:loop
set /a n=%random% %% 8
call set i=%i%%%s:~%n%,1%%
set /a m=m+1
if not %m%==8 goto loop:
echo %i%
pause
Actual output: 83254646
The desired output would be something like: 83254176
Thanks, Joel
Upvotes: 3
Views: 111
Reputation: 37569
this is imo faster (better with delayed expansion
, I know but don't like it here):
@ECHO OFF &SETLOCAL
for /l %%a in (1 1 8) do call set "$%%random%%%%a=%%a"
for /f "tokens=2delims==" %%a in ('set "$"') do <nul set/p"=%%a"
echo(
@ECHO OFF &SETLOCAL
for /l %%a in (1 1 8) do call set "$%%random%%%%a=%%a"
for /f "tokens=2delims==" %%a in ('set "$"') do call set "line=%%line%%%%a"
echo(%line%
Upvotes: 4
Reputation: 130819
The following randomly selects a digit from the source string, and then removes that digit from the source. It avoids the relatively slow GOTO, and performs the minimum number of iterations.
@echo off
setlocal enableDelayedExpansion
set "s=12345678"
set "i="
for /l %%N in (8 -1 1) do (
set /a "n1=!random! %% %%N, n2=n1+1"
for /f "tokens=1,2" %%A in ("!n1! !n2!") do (
set "i=!i!!s:~%%A,1!"
set "s=!s:~0,%%A!!s:~%%B!"
)
)
echo !i!
pause
Upvotes: 3
Reputation: 37569
you can put the number already done in an associative array:
@ECHO OFF &SETLOCAL
set "i="
set "s=12345678"
:loop
set /a n=%random% %% 8
if not defined $%n% (
call set "i=%i%%%s:~%n%,1%%"
set "$%n%=1"
) else (
goto:loop
)
set /a m+=1
if not %m%==8 goto:loop
echo %i%
Upvotes: 2