0

I feel very confused right now, I would like to have some insight on what is going on.

I am trying to write a batch script that would launch a random web browser when I double-click the icon. Easy enough.

Here's my first attempt:

set /a var=%random% %%7 + 1

if %var%==1 (start "brave" "C:\Program Files\BraveSoftware\Brave-Browser\Application\brave.exe")
if %var%==2 (start "chrome" "C:\Program Files (x86)\Google\Chrome\Application\chrome.exe")
if %var%==3 (start "edge" "C:\Program Files (x86)\Microsoft\Edge\Application\msedge.exe")
if %var%==4 (start "firefox" "C:\Program Files\Mozilla Firefox\firefox.exe")
if %var%==5 (start "libreWolf" "C:\Program Files\LibreWolf\librewolf.exe")
if %var%==6 (start "opera" "C:\Program Files\Opera\opera.exe")
if %var%==7 (start "vivaldi" "C:\Program Files\Vivaldi\Application\vivaldi.exe")

This works perfectly, nothing to complain about.

Now, I wanted to make my random picking a little bit cleaner, so I did this:

set /a minval=1
set /a maxval=7
set /a var=%RANDOM% * (%maxval% - %minval% + 1) / 32768 + %minval%

And here is where the strange stuff is happening.

When I double-click the icon, it keeps opening the same browser on and on (meaning, and I verified it, that var always has the same value). But when I start the script from the cmd, it works perfectly, as before.

What is going on?! How is the first attempt okay but not the second one? And why does it work from the command line and not from mouse input?

Adrian Mole
  • 49,934
  • 160
  • 51
  • 83
M.Connor
  • 30
  • 4
  • Does this answer your question? [Why is %random% in Windows time based and how to get a real random number?](https://stackoverflow.com/questions/59823766/why-is-random-in-windows-time-based-and-how-to-get-a-real-random-number) – phuclv Apr 17 '22 at 13:45

1 Answers1

2

The seed for the random number generator is the current time.

If you turn echo on, you'll find that the "random" number generated is changing slowly.

When you start your batch by clicking, a new process is created and the first value returned by %random% appears to be the seed, consequently when you apply your formula, the calculated value will remain constant for a substantial time. Using mod, the value will change more rapidly.

If you run the same batch multiple times from the prompt, the random seed belongs to the interactive cmd session, so the seed is not re-initialised for the next run.

One consequence of this scheme is that if a batch using random is executed at the same time of day (like by task scheduler) then the same sequence of numbers will be generated.

Magoo
  • 77,302
  • 8
  • 62
  • 84