Wednesday, June 27, 2007

Random Number Generation

If you ever need to get a random number while writing a Windows batch script, you can use Windows command's handy little %RANDOM% environment variable.

echo %RANDOM%

And if you want to generate a random number within a range of values, all you have to do is perform some simple command line math.  Say you want to generate a random number between 50 and 150.

set MIN=50

set RANGE=100

set /A RN=%RANDOM% % %RANGE% + %MIN%

That should do it.


Camilo Martin Momenti said...

really nice little blog =) i've read all your posts i think you should write more! x) comand-line is adictive xD

btw, how does that work???

x%y isn't (x/y)*100 ???
i thought it was =P

sorry for my english =)

oh, and i tried to make a useless effect out of boredom:

setlocal enabledelayedexpansion
for /L %%a in (1,1,10000) do set /A !random! % 2
setlocal disabledelayedexpansion

my idea was to get tons of 0s and 1s seizing the lack of CRLF of "set" comand used that way

but it says there's an operator missing O.O'

Arif Sukoco said...

Thanks Camilo. I'm glad you find the blog useful.
If you want to just print a series of 0's and 1's, you have to do it a little differently:

setlocal enabledelayedexpansion
set Y=
for /L %%a in (1,1,10000) do (
set /A X=!random! %% 2
set Y=!Y!!X!
echo !Y!
setlocal disabledelayedexpansion

I'm assuming here that you put these commands into a .bat or .cmd file. Notice that your modulo operator (% 2) needs to be "escaped" into (%% 2) otherwise you'll get that missing operator error. You also need to assign the result of your arithmetic SET into a variable.