0

There is an easy way to make a number generator.
But I just want the generated numbers to be 1 - 4

The following program takes too long to get an output

@echo off
:RUN
set /a Num=%random%
if %num% LEQ 4 echo %num%
goto :RUN

It runs %random% until it gets less than 4, which could be quite a while.

Moonicorn
  • 91
  • 1
  • 2
  • 9
  • Look at the output for `for /?` - specifically the section about `for /L`. Or did you want an infinite loop of numbers between 1 and 4? – SomethingDark May 29 '15 at 04:24
  • `set /a NumBetween1and4=%random% %% 4 + 1` – Aacini May 29 '15 at 05:02
  • possible duplicate of [How to use random in BATCH script?](http://stackoverflow.com/questions/5777400/how-to-use-random-in-batch-script) – indiv May 29 '15 at 05:42

1 Answers1

0

You can mask the bits in the random value (And operation = & operator) to retrieve the lower two, getting a number in the range [0,3] and adding 1 to adapt to the indicated range

set /a "num=(%random% & 3) + 1"

Or, as the random value generated uses 15 bits, it can be shifted to retrieve only the two upper bits

set /a "num=(%random% >> 13) + 1"

The parenthesis are needed in both cases because + operator has higher precedence than & or >> operators.

You can also use a Mod operation (% operator) to retrieve the remainder from a division by 4, also getting a number in the range [0,3]

set /a "num=%random% %% 4 + 1"

The % operator (inside batch files the % has to be escaped so it becomes %%) has higher precedence than the + operator, so here parenthesis are not needed.

MC ND
  • 69,615
  • 8
  • 84
  • 126