Reputation: 128
The following script:
@echo off
setlocal EnableDelayedExpansion
set n=0
for /R %%f in (./*.avi;./*.mp4) do (
set /A n+=1
set "file[!n!]=%%f"
)
set /A "rand=(n*%random%)/32768+1"
ECHO %rand%
ECHO "!file[%rand%]!"
endlocal
PAUSE
Returns the same random number and therefore file every execution. Please could you suggest a solution with a detailed description of why the problem was occurring.
Thank you
Upvotes: 2
Views: 141
Reputation: 350310
I was not able to reproduce this, but if the problem is related to %random% being queried with tiny intervals and it only changes in small quantities, then another formula might be a solution. With the following alternative you get a different output even if %random% only changes with 1:
set /A "rand=(%random% %% n)+1"
Upvotes: 1
Reputation: 70933
The PRNG used by cmd
is initialized using the current time, with a one second resolution, once per cmd
instance (this behaviour was exposed here). Two separate cmd
instances started in the same second will generate the same pseudo random sequence.
But sucesive executions of the same or different batch files inside the same cmd
instance will retrieve different (or not, it is random) "random" sequences.
In the first case, with separate instances started at the same or near seconds, you can obtain the indicated behaviour exposed in your question, but the problem is increased by the arithmetics in your code.
If n
is the same or similar for each execution, and %random%
return a value near the one returned in the previous execution (as you describe), then n*%random%
will return a result near to one in the previous execution. Divided by 32768 any difference will be discarded and you end with the same selected file.
In this case it is better to use the modulo operator. Being the remainder of the division, it is easier to get a different result from only slightly different starting random value
set /a "rand=%random% %% n + 1"
Upvotes: 1