1

In my batch program, I have this line in the middle of it:

set /a scramble=%random%

The problem here is that everytime I open the batch file, it gives me the same output, for example I open it and it sets %scramble% to 17534, the next time I open it, it is very similar, for example 17546, increasing by a small amount. If I loop it, then only the first random number is similar, all the rest are random.

For example The first time I run it, it gives me this list of numbers:

23486,32645,4854

the second time it gives

23498,26374,17322

So only the first is similar.

A simple workaround is to put echo %random% and then cls in the beginning of the batch, so it's not a problem for me, but I'm just wondering why this is?

Jason Faulkner
  • 6,378
  • 2
  • 28
  • 33
sdfs
  • 15
  • 2

1 Answers1

0

Random number generator in cmd uses the current time (with second resolution) to seed the prng. This initialization is done once per cmd instance.

So, if you are running your batch file in a new cmd instance each time, the seed is very similar in each case.

But if you start your batch file several times inside the same cmd instance, the sequences will not be so similar as the initialization is done only once.

More information can be found here

Community
  • 1
  • 1
MC ND
  • 69,615
  • 8
  • 84
  • 126
  • *"But if you start your batch file several times inside the same cmd instance, the sequences will not be so similar as the initialization is done only once."* - I don't understand your point, especially since you know that if several batch processes start within the same second, they each get the same "random" sequence. I interpret your sentence to mean the opposite. – dbenham Jan 11 '15 at 14:28
  • @dbenham, take this `x.cmd` batch file `@echo %random%`. Now, from command line execute `for /l %a in (1 1 10) do @start /b cmd /c x.cmd` and then execute `for /l %a in (1 1 10) do @call x.cmd`. PRNG is initialized once per **`cmd` process**, not per batch file execution. The *inside the same cmd instance* makes the difference – MC ND Jan 11 '15 at 15:37