This approach ensures that no collisions occur, that is, the generated random numbers are unique:
@echo off
setlocal EnableExtensions EnableDelayedExpansion
set "ARG=%~1"
set /A ARG+=0
if %ARG% LSS 1472 (goto :FEW) else (goto :MANY)
:MANY
for /L %%I in (0,1,32767) do (
set "RND_!RANDOM!=%%I"
)
set /A COUNT=0
for /F "tokens=2 delims==" %%J in ('set RND_') do (
set /A COUNT+=1
if !COUNT! GTR %ARG% goto :SKIP
ECHO copy /B nul "file%%J.txt"
)
:SKIP
goto :END
:FEW
set /A COUNT=0
:LOOP
if %COUNT% GEQ %ARG% goto :CONT
set /A COUNT+=1
set "RND_%COUNT%=%RANDOM%"
set /A TEST=COUNT-1
for /L %%I in (1,1,%TEST%) do (
if !RND_%%I! EQU !RND_%COUNT%! (
set /A COUNT-=1
)
)
goto :LOOP
:CONT
for /L %%J in (1,1,%COUNT%) do (
ECHO copy /B nul "FILE!RND_%%J!.txt"
)
goto :END
:END
endlocal
exit /B
Call the above script with the number of random files as a command line argument.
The script contains two routines for generating the random numbers:
:FEW
: The random numbers are collected in an array-style variable RND_#
where #
represents the index from 1
up to the number of items to be generated. Every newly generated number is compared against all previous ones and whenever a match is found, generation is repeated, until the total amount is reached. Finally the empty random files are generated.
:MANY
: Unique random numbers are generated with an approach similar to the one of this post: How to generate a list of random numbers without duplicates in pure batch scripting?
Depending on the number of random files to be created, the appropriate routine is selected. The routine :FEW
is good for only a few random numbers; as soon as the total number increases, the probability of receiving duplicates and hence the said repetition of the random number generation makes it quite inefficient.
The routine :MANY
is slow for a few random numbers because there is always a random sequence of 32768
items generated; as soon as the total amount increases, this method is the better choice for the sake of overall performance.
The used limit number 1472
below which the :FEW
routine is chosen is just an arbitrary value here.
There are upper-case ECHO
commands prefixed at the copy
commands for testing. Whenever you want to actually create any files, simply remove them.