B
B
bitbuff2017-07-23 02:22:59
Python
bitbuff, 2017-07-23 02:22:59

How to get a random number in a range with exceptions?

For example, in python there is a function randint(min, max), which gives a random number in the range from min to max.
I need a function that will take an array of exceptions: randint_se(min, max, exceptions), where exceptions is an array of those numbers that should not fall into the range. The exceptions array can be of any length.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
B
bitbuff, 2017-07-23
@bitbuff

I thought and solved the problem. Maybe someone will come in handy.

import random

def randint_se(min, max, exceptions):

  possible = []
  exceptions.sort()

  for number in range(min, max+1):
    count = 0
    for exception_number in exceptions:
      if number == exception_number:
        break
      count += 1
    if count == len(exceptions):
      possible.append(number)


  return random.choice(possible)

N
NtropyNN, 2017-07-24
@NtropyNN

My take is
to adjust the maximum value to take into account the lengths of all excluded ranges, get a random number for the updated range, and then apply the list of excluded ranges to adjust the value.
Example: given to return a number from 1 to 6 (dice), but the number 4 is considered forbidden.
Solution: get a random number from 1 to 5 and if it is greater than and equal to 4, add to the result 1 (the length of the excluded range).

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question