Krontical
Krontical

Reputation: 39

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

I'm trying to preform a task in batch that generates random numbers in a specific range which I have already done using the code listed below.

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

Additionally a set of numbers should be also avoided which I could not implement by myself up to now.

What I mean is a batch file that would generate numbers between 1-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.

Upvotes: 3

Views: 206

Answers (4)

MC ND
MC ND

Reputation: 70923

For a value in the range 1-99, just ensure the last digit fall in the 1-9 range

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

Alternatively, if the range is 1-100 and the 100 must be included in the list of allowed values

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

In this case, the source range 1-91 (that is 1-100 except the problematic numbers) is mapped to the target range 1-100 adding the adecuated values to skip the excluded numbers

Upvotes: 1

Magoo
Magoo

Reputation: 80023

@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

You say you don't want to produce ?0 but you did not say you did not want 100. This procedure generates without (10 20 30 40 50 60 70 80 90). If you also want to exclude 100, then remove the IF %setvar% neq 100

Upvotes: 2

npocmaka
npocmaka

Reputation: 57252

@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%

Upvotes: 2

Mofi
Mofi

Reputation: 49086

This is quite 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 a random number is calculated in range 0 to 99 by dividing a random number by 100 and assigned just the remainder to the environment variable.

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

If this remainder is 9 and the number is not 99, the number would be 10, or 20, or 30, ... after adding 1 in last step. Therefore the numbers 9, 19, 29, 39, ... must be ignored by run the entire calculation once more with a new random number.

Upvotes: 1

Related Questions