% random% in a batch and how to avoid certain numbers in a certain range?

I am trying to do a task in a batch that generates random numbers in a specific range, which I have already done using the code below.

set /a setvar=%random% %% 100+0

      

In addition, a set of numbers should be avoided that I would not have been able to implement myself until now.

I mean a batch file that will generate numbers from 1 to 100, but avoid the numbers 10, 20, 30, 40, 50, 60, 70, 80 and 90.

Is there any solution for this? I'm at a loss.

+3


source to share


4 answers


@echo off
setlocal
:: set list of values that should be avoided
for /l %%N in (10,10,90) do (
    set "_%%N=."
)


    set /a setvar=%random% %% 100+1
    :: if value is in the list sums the set value with 
    :: random value between 0 and 9 getting modulus of 9 
    if defined _%setvar% (
        set /a setvar=setvar +  %random% %% 9 + 1
    )


echo %setvar%

      



+2


source


@ECHO OFF
SETLOCAL
:GetNumber
set /a setvar=%random% %% 100 + 1
IF %setvar% neq 100 IF %setvar:~-1%==0 GOTO getnumber
echo Random number is %setvar%

GOTO :EOF

      



Are you saying you don't want to produce? 0, but you didn't say you didn't want to 100

. This routine is generated without (10 20 30 40 50 60 70 80 90). If you also want to exclude 100, removeIF %setvar% neq 100

+2


source


It's pretty easy to achieve:

@echo off
:GetNumber
set /a Number=%random% %% 100
set /a Remainder=Number %% 10
if %Remainder% == 9 if not %Number% == 99 goto GetNumber
set /a Number+=1
echo Random number is %Number%

      

First, the random number is calculated from 0 to 99 by dividing the random number by 100 and only the remainder of the environment variable is assigned.

This random number is divided by 10 to get the remainder.

If this remainder is 9 and the number is not 99, the number will be 10, or 20 or 30, ... after adding 1 in the last step. Therefore, the numbers 9, 19, 29, 39, ... should be ignored by re-running the whole calculation with a new random number.

+1


source


For a value in the range 1-99, just make sure the last digit falls in the range 1-9

set /a "setvar=(%random% %% 100 / 10 * 10) + (%random% %% 9 + 1)"

      

Alternatively if the range is 1-100 and 100 should be included in the list of valid values

set /a "x=%random% %% 91 + 1", "x=x+(x-1)/9", "x=x-x/100"

      

In this case, the original range 1-91

(that is 1-100

, excluding problematic numbers) is mapped to the target range 1-100

by adding highlighted values ​​to skip the excluded numbers

+1


source







All Articles