Tuesday, February 1, 2011

Batch Scripting Fun: Playing with Random Numbers

Proof of Concept:

Today, I needed to generate a random number between 1 and 5. Depending on what random number came up, would determine what IP address from a pool of IP address the user would be assigned.

Maybe I had Craps on the mind, but this problem reminded me of dice rolling. All-be-it a 5 sided die. So to test, I thought that I would write a simple Batch script that would generate a random number between 1 and 5.

I had a pretty good idea that I would use the %Random% operation to generate a random number between 0 – 32767. Then I would limit that to between 1 and 5.

My first attempt turned out like this:

:loop
set num=%random%
if /i %num% GTR 5 goto loop
if /i %num% LSS 1 goto loop
goto finish
:finish
echo %num%
pause >nul
exit

Now it worked but it was slow because if you think about it, I would have to recalculate %random% every time the number was greater than 5 or less then 1. I needed to speed this up.


I knew that math would be the answer. I came across this Simulate a Dice Roll through a Google search. It showed that I was on the right track. I just tweaked it a little to at some logic to be able to run a command after finding the random number between 1 and 5.

@echo off
cls

:RandomLoop
set /A num=%random% %% 5 + 1
goto NumberFound

:NumberFound
if %num%==1 goto one
if %num%==2 goto two
if %num%==3 goto three
if %num%==4 goto four
if %num%==5 goto five

:one
REM Enter next item to do here
echo %num%
exit

:two
REM Enter next item to do here
echo %num%
exit

:three
REM Enter next item to do here
echo %num%
exit

:four
REM Enter next item to do here
echo %num%
exit

:five
REM Enter next item to do here
echo %num%
exit

:end
exit

As you see. The random number is generated and depending on the number 1 through 5, the next set in the Batch script can be executed. While this is a very simple programming 101 type of question, this shows how you can turn an classroom exercise into a practical application.