Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Random Variables in Batch Files

I am trying to create a random variable between 0 and 3 with a batch file. Right now I have the following code:

@echo off
set /a var=%random%/8192
@echo %var%
Pause

This batch file returns "2" every time. If I type the same commands into the command line directly it returns 0 through 3.

Any related knowledge would be appreciated :)

like image 931
Nick Avatar asked Jan 02 '26 08:01

Nick


2 Answers

EDIT: I changed my answer because the OP changed his question: originally the range of desired random numbers was 0 to 4...

The right formula is:

set /a var=%random% * 4 / 32768

The use of other operators instead (like / or %) modify random number distribution, so you will get a repeated result more frequently than with the right formula.

EDIT: Additional explanations added

Previous code should correctly works in your example above. However, if your code is placed inside a code block (enclosed in parentheses), then you must use Delayed Expansion (as other people indicated in their answers) in all variables that may be modified inside the block, including RANDOM. For example:

@echo off
setlocal EnableDelayedExpansion
:ProgStart
(
set /a var = !random! * 4 / 32768
goto target!var!
)

If you wish, you may use this simpler formula that gives equivalent results (random numbers between 0 and 3):

set /a var = !random! / 8192
like image 105
Aacini Avatar answered Jan 05 '26 04:01

Aacini


The actual command you want is:

set /a var=%random% %% 4

This will give you: 0, 1, 2 or 3.

If you are doing this inside a FOR-loop use !..!-type variable instead of %..%-type variables in which case you will also need setlocal enabledelayedexpansion somewhere near the beginning of your batch file.

like image 31
Paul Tomasi Avatar answered Jan 05 '26 06:01

Paul Tomasi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!