2

I need a batch file randomizer to randomly select 5 numbers from 1-30 then output them. I have researched and found nothing that is useful to me. I am a Beginner so if you could make the code simple and explain it so i can reproduce it later if i need it again.

user2975367
  • 917
  • 1
  • 7
  • 7

2 Answers2

3

batch noob answer is absolutly correct, but can generate duplicated numbers. For an option with no duplicate numbers,

@echo off

    setlocal enableextensions

    for /F "tokens=2" %%l in ('cmd /v:on /c "@for /L %%n in (1 1 30) do @echo ^!random^! %%n"^|sort^|more +25') do (
        echo %%l
    )

It spawns a cmd (cmd /v:on /c "....") to generate a list of numbers 1-30 prefixed with a random number, this list is then sorted (sort), using the random number as key. Once sorted, more +25 is used to skip the first 25 numbers in list, and then, a for /F is used to step over the 5 last lines, taking the second token from it (the lines contains the random number and the number from 1-30) and echoing it to console

MC ND
  • 69,615
  • 8
  • 84
  • 126
  • 1
    +1, Good idea, but your script will give the exact same sequence if run multiple times within 1 second because of the [random number seed issue](http://stackoverflow.com/a/19694573/1012053) when CMD.EXE is launched. Better to write the list of random numbers to a file without launching new CMD.EXE, and then read the file with FOR /F. – dbenham Nov 13 '13 at 00:38
1

Use RANDOM -- that's what you are looking for.

RANDOM gives a number between 0 and 32767.

Example:

set /a num=%random% 
echo.%num%

This will output a number between 0 and 32767.


But if you want to reduce that number do this:

set /a num=%random% %%5
echo.%num%

This will output a number between 0 and 4.


In your case (range 1 to 30) do this:

set /a num1=%random% %%30 +1
set /a num2=%random% %%30 +1
set /a num3=%random% %%30 +1
set /a num4=%random% %%30 +1
set /a num5=%random% %%30 +1

echo %num1%
echo %num2%
echo %num3%
echo %num4%
echo %num5%

Hope it helps! :D

aschipfl
  • 33,626
  • 12
  • 54
  • 99
QbicSquid
  • 165
  • 1
  • 5