Author Options:

Batch/.bat Programing Answered

I would like to create a variable that is between two preset numbers but they are randomly created that runs in a batch program. For example if I wanted to create a program that would act like a dice where there is a 1/6 chance (for a 6 sided dice) of the dice landing on any number between 1 and 6.


The forums are retiring in 2021 and are now closed for new topics and comments.

Best Answer 9 years ago

That's one of the possibilities:

set /a "min = 1"
set /a "max = 6"

set /a "rdm = (((%random% & 1) << 30) | (%random% << 15) | %random%) %% (max - min + 1) + min"

echo %rdm%

Prof. Pickle
Prof. Pickle

8 years ago

Slow down g-one, you'll give the poor boy a heart attack.

(Not that I'm questioning your talent)

g-one's explanation was spot on, but I've got a different, simpler way.

set /p min=
set /p max=
set /a max=%max%-%min%
set /a number=%random% %% %max% + %min%
echo %number%

This should almost always work, sometimes the number is 1 bigger or 1 smaller than what you want it to be.


9 years ago

Have you done any searches for "generating a random number in a batch file"? When i Googled that phrase the first 2 links pretty much covered all you would need. There is allot of information out there about this sort of thing. Its just a matter of looking for it.