Random number generation problem

Discussion forum for all Windows batch related topics.

Moderator: DosItHelp

Post Reply
Message
Author
gotouser
Posts: 7
Joined: 26 Feb 2018 07:36

Random number generation problem

#1 Post by gotouser » 16 May 2018 11:28

Hello,
I wrote a script that would call a random batch file out of 154 files in total. I wanted to have some files to have a higher chance of being called than others, so I wrote this:


:randomization
cls
set /a randoma=%random% %% 10+1
if %randoma%==1 goto random1
if %randoma%==2 goto random1
if %randoma%==3 goto random1
if %randoma%==4 goto random1
if %randoma%==5 goto random1
if %randoma%==6 goto random2
if %randoma%==7 goto random2
if %randoma%==8 goto random2
if %randoma%==9 goto random2
if %randoma%==10 goto random3

:random1
set /a randomx=%random% %% 99 + 1
call %randomx%.bat
goto randomization

:random2
set /a randomy=%random% %% 137 + 100
call %randomy%.bat
goto randomization

:random3
set /a randomz=%random% %% 154 + 138
call %randomz%.bat
goto randomization


This works most of the time, but sometimes I get an error message saying that "the command (insert number that is higher than 154).bat does not exist" (for example "the command 198.bat does not exist). Does anyone know why this happens and/or how to fix it?

ShadowThief
Expert
Posts: 1166
Joined: 06 Sep 2013 21:28
Location: Virginia, United States

Re: Random number generation problem

#2 Post by ShadowThief » 16 May 2018 15:16

Code: Select all

set /a randomz=%random% %% 154 + 138
means "pick a random number between 0 and 153 and then add 138 to it." If the random number is 153, the result will be 291. In order to avoid going past the upper number, you need to first subtract the number you're adding on from the amount you're increasing it by. Since the largest number is 154, you need to generate a random number between 0 and 16.

Code: Select all

set /a randomz=%random% %% 16 + 138
The code in :random2 should also be updated accordingly.

pieh-ejdsch
Posts: 240
Joined: 04 Mar 2014 11:14
Location: germany

Re: Random number generation problem

#3 Post by pieh-ejdsch » 17 May 2018 09:28

This can be short

Code: Select all

:randomization
cls
Set /a RadomA =%random% %%10 +1
Rem 1 - 100
Set /a randomBat =%random% %%99 +1
rem 101 - 137
if %randomA% gtr 5 set /a randomBat = %random% %%(137 -100 -1) +101
rem 138 - 154
if %randomA% gtr 9 set /a randomBat =%random% %%(154 -137 -1) +138
call %randomBat%.bat
Goto :randomization
Phil

Post Reply