Generating two random coordinates in windows batch file

Viewed 39

I intended to output the following in a Windows batch file to print five random coordinates wihtin a given range. I know this task is easier on other languages but I'm forced to use Windows batch programming.

INTENDED OUTPUT:

x1:1344
y1:1995
x1:1347
y1:1998
x1:1350
y1:1996
x1:1345
y1:1999
x1:1345
y1:1995
)

My windows batch coding is not that great and I complied the following using Google Fu. I'm not sure what I'm missing but the following code is supposed to output two random numbers as a coordinate (x1 and y1).
However my code below does not give me my intended output

CODE

@echo off & setlocal EnableDelayedExpansion

for /L %%a in (1 1 5) do (
        REM Random X coordinate between 1336 1350)       
        call:rand 1336 1350      
        set /A x1= !RAND_NUM!        
        echo(!x1!)

        REM Random Y coordinate between 1950 2000)
        call:rand 1950 2000
        set /A y1= !RAND_NUM!
        echo(!y1!)
)

goto:EOF

:rand
SET /A RAND_NUM=%RANDOM% * (%2 - %1 + 1) / 32768 + %1
goto:EOF

My output is missing the five y coordinates and prints the first five x coordinates first and then one y coordinate and stops.

OUTPUT:

x1:1344
x1:1349
x1:1347
x1:1342
x1:1347
y1:1995)
1 Answers

The closing parenthesis ) inside of the code block is seen as the closing parenthesis of the code block itself, if you really needed them, which you don't you would need to escape them ^) but instead remove them entirely. Also no need to set /A x1 and y1 just set can work on its own, but even that set is not needed:

@echo off & setlocal EnableDelayedExpansion

for /L %%a in (1 1 5) do (
        REM Random X coordinate between 1336 1350
        call:rand 1336 1350           
        echo(x1:!RAND_NUM!

        REM Random Y coordinate between 1950 2000
        call:rand 1950 2000
        echo(y1:!RAND_NUM!
)
goto:EOF

:rand
set /A RAND_NUM=%RANDOM% * (%2 - %1 + 1) / 32768 + %1
goto :EOF
Related