Reputation: 21
please give me the code for generating 4 digit random number in dos (batch) file
i tried
set /a num=%random% %%10000 +1
but this is not giving exactly 4 digit number every time. so please help me.
Upvotes: 1
Views: 6389
Reputation: 11
Try this:
set num=0000%random%
set num=%num:~-4%
This will generate a random number between 0000 and 9999
Upvotes: 0
Reputation: 9266
You don't say whether you need uniformity over the entire range, or if you just want a quick 4-digit number for a filename.
One super quick way is to limit your range to 1000-9999
set /a num = %random% %% 9000 + 1000
If you want the full range from 0000-9999
, you can take a larger number and truncate to get the last four digits, but only after guaranteeing that you have at least four digits. To do this, add 1000 to the number before truncating.
set /a num = %random% + 1000
set num=%num:~-4%
This still suffers from a uniformity problem. Numbers between 0000-2767
will appear about 33% more often than numbers between 2768-9999
, because of the way %random%
generates numbers.
One way to reduce this error (but not eliminate it) is to take the result of several %random%
calls together.
set num=%random:~-1%%random:~-1%%random:~-1%%random:~-1%
In this case, digits 0-7
are still about 0.1% more likely than 8-9
, which is good enough for most anything.
BUT, if you want to remove the error entirely, you can do so with a loop.
:rndloop
set /a num = %random% + 1000
if %num% GEQ 31000 goto :rndloop
set num=%num:~-4%
This loop will always give you a uniform distribution between 0000 and 9999.
Credit to @aschipfl, @Manuel, @Stephan, and @Magoo for the parts of their answers borrowed here.
Upvotes: 1
Reputation: 56180
just to add another possibility:
echo %random:~-1%%random:~-1%%random:~-1%%random:~-1%
(take the last digit from four randoms)
Upvotes: 4
Reputation: 80023
Crudely,
:rndloop
set /a random_number=%random%+10000
if %random_number% geq 40000 goto rndloop
set "random_number=%random_number:~-4%"
echo %random_number%
If you actually want a random number in range 0..9999 then try
:rndloop
set /a random_number=%random%
if %random_number% geq 30000 goto rndloop
set /a random_number=random_number/3
echo %random_number%
Assuming %random% is linear between 0 and 32767, then numbers greater than 29999 must be dismissed as using them would bias the distribution:
800 would be generated for %random%=800 or 10800 or 20800 (3 possible)
200 would be generated for %random%=200 or 10200 or 20200 or 30200 (4 possible)
Upvotes: 0
Reputation: 46
Try this:
set random_number=%random:~-4%
This will generate a 4digit random number
Upvotes: 0