3

在 Windows 命令行上,是否可以随机重新排列数字?

例如,我在批处理文件中有以下逻辑,它从 s 中随机选择数字。这是允许重复项目。我希望这些项目不重复。

@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

实际输出:83254646

所需的输出类似于:83254176

谢谢,乔尔

4

3 回答 3

4

这是 imo 更快(更好delayed expansion,我知道但不喜欢这里):

@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%
于 2013-10-20T05:47:43.413 回答
3

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
于 2013-10-20T03:30:52.530 回答
2

您可以将已经完成的数字放入关联数组中:

@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%
于 2013-10-19T20:18:06.523 回答