2

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

2 Answers 2

1

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"
Sign up to request clarification or add additional context in comments.

Comments

1

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"

2 Comments

Could you please edit in an explanation of why this syntax answers the question? Code-only answers are discouraged, because they don't teach the solution.
Indeed, that was too short. I've edited my answer. Thank you.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.