将输入随机播放到DOS中的循环命令

问题描述 投票:0回答:1

在Windows命令行中,我使用的命令类似于

for %x in (1 2 3) do echo %x

有没有办法以随机顺序处理输入集(1,2,3)?这样的结果可能是

2
3
1

任何类型的伪随机排列对我来说也没问题,它也不一定是'真正的'洗牌。

windows for-loop command-line
1个回答
1
投票

这是我在这里的第一个答案,所以我们将看到它是怎么回事。

我做了一些研究,并没有找到任何专门用于改组for命令的输入,但我确实发现你可以将你的输入存储在批处理数组中并对其进行一些改组。但是,这确实意味着不使用for命令。

这是我用来生成混洗数组的代码:

@echo off
setlocal enabledelayedexpansion
set inputVars[0]=1
set inputVars[1]=2
set inputVars[2]=3
set inputVars[3]=4
set inputVars[4]=5

set /A inputsLength=0

:lengthLoop
if defined inputVars[%inputsLength%] (
    set /A inputsLength+=1
    goto :lengthLoop
)

set /A currentIndex=0

:loop
    set /A randIndex=%RANDOM% %%%inputsLength%

    set temp=!inputVars[%currentIndex%]!
    set inputVars[%currentIndex%]=!inputVars[%randIndex%]!
    set inputVars[%randIndex%]=%temp%

    set /A currentIndex+=1

if currentIndex LSS %inputsLength% (
    goto :loop
)

set /A currentIndex=0

:outputLoop
if defined inputVars[%currentIndex%] (
    echo !inputVars[%currentIndex%]!
    set /A currentIndex+=1
    goto :outputLoop
)

endlocal

数组初始化后的第一位代码为方便起见找到了数组的长度。长度可能看起来很明显,但我不确定你是如何得到你的输入或填充阵列所以我继续并添加它。

set /A inputsLength=0

:lengthLoop
if defined inputVars[%inputsLength%] (
    set /A inputsLength+=1
    goto :lengthLoop
)

第二位实际上通过使用%RANDOM%来进行混洗。我用this问题作为参考。

set /A currentIndex=0

:loop
    set /A randIndex=%RANDOM% %%%inputsLength%

    set temp=!inputVars[%currentIndex%]!
    set inputVars[%currentIndex%]=!inputVars[%randIndex%]!
    set inputVars[%randIndex%]=%temp%

    set /A currentIndex+=1

if currentIndex LSS %inputsLength% (
    goto :loop
)

代码的最后一位实际上遍历数组,因此替换for命令以使其工作。

set /A currentIndex=0

:outputLoop
if defined inputVars[%currentIndex%] (
    echo !inputVars[%currentIndex%]!
    set /A currentIndex+=1
    goto :outputLoop
)

我希望这有助于或者至少让您考虑实现您的想法的可能方式。

© www.soinside.com 2019 - 2024. All rights reserved.