tenthplanet0
tenthplanet0

Reputation: 373

How to get a random number from a range, excluding some values

In C#, how do I get a random number from a range of values - like 1..100, but that number should not be in some specific list of values, like 5, 7, 17, 23?

Upvotes: 36

Views: 60995

Answers (11)

Jonathan Barraone
Jonathan Barraone

Reputation: 487

Try this:

public static int GetRandomNumber(int Min, int Max, int[] ExcludedNumbers)
    {
        Random randomGenerator = new Random();
        int currentNumber = randomGenerator.Next(Min, Max + 1);

        while (ExcludedNumbers.Contains(currentNumber))
        {
            currentNumber = randomGenerator.Next(Min, Max + 1);
        }
        return currentNumber;
    }

Here is an example of its usage:

int randomNumber = GetRandomNumber(1, 100, new int[] { 5, 7, 17, 23 });

Upvotes: 0

DjordjePeri
DjordjePeri

Reputation: 1

Edit: Only for Unity3D, I didn't know that Random is a class from Unity. Still it might help someone, so I'll leave it here.

I'm super late to answer the question, but let's contribute to the conversation. This is my expansion of the already known Random.range(x,y), without lists or something more complicated:

public static int RandomExceptList(int min, int max, int[] forbiddenElements) 
{
    bool numberAllowed = true;
    
    for(int i=0;i<forbiddenElements.Length;i++)
    {
        if(forbiddenElements[i]<min || forbiddenElements[i]>max)
        {
            Debug.Log("All forbidden numbers have to be inside given range.");
            return min;
        }
        for (int j=i+1; j<forbiddenElements.Length;j++)
        {
            if(forbiddenElements[i]==forbiddenElements[j])
            {
                Debug.Log("Forbidden numbers have to be different between each other.");
                return min;
            }
        }
    }
        
    if (max<min)
    {
        Debug.Log("Minimum limit has to be lower than maximum limit...");
        return min;
    }
    
    if (forbiddenElements.Length>(max-min))
    {
        Debug.Log("You can't forbid so many numbers.");
        return min;
    }
    
    if (forbiddenElements.Length>=1)
    {
        //this part here checks indefinitely for an allowed randomly generated number (outside "forbiddenElements" array). Eventually it will find it and return it and therefore terminate the loop.
        while(true)
        {
            numberAllowed=true;
            
            int r = Random.Range(min,max+1);
        
            for(int i=0;i<forbiddenElements.Length;i++)
            {
                if (r==forbiddenElements[i])
                    numberAllowed=false;
            }
            if(numberAllowed)
                return r;
        }
    }
    else
    {
        int r = Random.Range(min,max+1);
        return r;
    }
}

Note that in this case, you must always enter a forbiddenElements parameter, even if it's an empty array. Random.range doesn't use top limit in the number pool, so I've added "max+1". Hope this helps

Upvotes: 0

user1373996
user1373996

Reputation:

From Java, but I'm pretty sure you can change the language easily :)

Solution:

    /**
     * Get a random number between a range and exclude some numbers
     *
     * @param start start number
     * @param end end number
     * @param excludes list of numbers to be excluded
     * @return value between {@code start} (inclusive) and {@code end} (inclusive)
     */
    private int getRandomWithExclusion(int start, int end, List<Integer> excludes) {
        Collections.sort(excludes); // this method only works with sorted excludes

        int random = start + new Random().nextInt(end - start + 1 - excludes.size());
        for (int exclude : excludes) {
            if (random < exclude) {
                break;
            }
            random++;
        }
        return random;
    }

Upvotes: 1

Mayer Spitz
Mayer Spitz

Reputation: 2525

This is the Extention method I use:

Random random = new Random();
public static int RandomNumber(int minN, int maxN, IEnumerable<int> exNumbers)
    {
        int result = exNumbers.First(); 
        while (exNumbers.ToList().Contains(result))
        {
            result = random.Next(minN, maxN + 1);
        }
        return result;
    }

Upvotes: 1

Ahmed Mansy
Ahmed Mansy

Reputation: 145

you can use a do-while statement to pick another Random if it equals what number you want to exclude. this code is to exclude the number you picked before

    int newNumber;
do {
    newNumber = Random.Range (0, 100);
} while(number == newNumber);

number = newNumber;

Upvotes: 3

Voicu
Voicu

Reputation: 17850

If you care about Big O, check out this algorithm. It assumes that the excluded values array is sorted in ascending order and contains values within 0 and n-1 range (inclusive).

public static int random_except_list(int n, int[] x) 
{
    Random r = new Random();
    int result = r.Next(n - x.Length);

    for (int i = 0; i < x.Length; i++) 
    {
        if (result < x[i])
            return result;
        result++;
    }
    return result;
}

If you call it with:

random_except_list(8, new int[]{3,4,6})

it will return one of the following values: 0, 1, 2, 5, 7.

Upvotes: 10

Maher Manoubi
Maher Manoubi

Reputation: 625

This is what I do in this situation, it's not perfect but works well for me. I usually do it only for 1 number but this is how it can be for a group of excluded numbers:

Let's say I want to exclude [5, 7, 17, 23] from a random between 1-100. I always have a substitution for each of the excluded numbers such as [6, 8, 18, 24]. If the random number falls into any of the excluded numbers, I replace it with its substitution.

I came here looking for a better solution but I couldn't find any so I ended up sharing mine.

Upvotes: 1

Bridge
Bridge

Reputation: 30651

Since no-one has posted any example code:

private int GiveMeANumber()
{
    var exclude = new HashSet<int>() { 5, 7, 17, 23 };
    var range = Enumerable.Range(1, 100).Where(i => !exclude.Contains(i));

    var rand = new System.Random();
    int index = rand.Next(0, 100 - exclude.Count);
    return range.ElementAt(index);
}

Here's the thinking:

  1. Build a Hashset of numbers you want to exclude
  2. Create a collection of all the numbers 0-100 which aren't in your list of numbers to exclude with a bit of LINQ.
  3. Create a random object.
  4. Use the Random object to give you a number between 0 and the number of elements in your range of numbers (inclusive).
  5. Return the number at that index.

Upvotes: 57

kol
kol

Reputation: 28688

Put the allowed numbers into an array, generate a random integer from 0 to the length of this array minus one. Use this integer as an index to get the random number itself from the array of allowed numbers.


If the original array contains large objects instead of numbers, then making another array by deep copying the allowed objects won't be effective. In this case, the array of allowed objects should contain only a pointer, a reference, or an index to the objects in the original array. In this case you generate a random integer to select one element of this array, and use this pointer/reference/index to get the selected object itself from the original array.

Here is a working example for the general case (just one possible solution!):

using System;
using System.Collections.Generic;

public static class RandomElementSelector
{
    public static IList<T> CollectAllowedElements<T>(IList<T> allElements, IList<T> excludedElements)
    {
        List<T> allowedElements = new List<T>();
        foreach (T element in allElements)
            if (!excludedElements.Contains(element))
                allowedElements.Add(element);
        return allowedElements;
    }

    public static T SelectRandomElement<T>(IList<T> allowedElements)
    {
        Random random = new Random();
        int randomIndex = random.Next(allowedElements.Count);
        return allowedElements[randomIndex];
    }

    public static T SelectRandomElement<T>(IList<T> allElements, IList<T> excludedElements)
    {
        IList<T> allowedElements = CollectAllowedElements(allElements, excludedElements);
        return SelectRandomElement(allowedElements);
    }
}

public class Test
{
    public static void Main()
    {
        const int N = 100;

        // Example #1
        int[] allNumbers = new int[N];
        for (int i = 0; i < allNumbers.Length; ++i)
            allNumbers[i] = i + 1;
        int[] excludedNumbers = { 5, 7, 17, 23 };
        Console.WriteLine(RandomElementSelector.SelectRandomElement(allNumbers, excludedNumbers));

        // Example #2
        List<string> allStrings = new List<string>();
        for (int i = 0; i < N; ++i)
            allStrings.Add("Item #" + (i + 1));
        string[] excludedStrings = { "Item #5", "Item #7", "Item #17", "Item #23" };
        Console.WriteLine(RandomElementSelector.SelectRandomElement(allStrings, excludedStrings));
    }
}

Upvotes: 0

Saint
Saint

Reputation: 480

Use a function to generate random numbers between 1 and 100, than write an if statement e.g. if random number is equal to 5, 7, 17, 23, generate the random number again, else use the random number that was generated in the first place.

Upvotes: -1

stmfunk
stmfunk

Reputation: 683

Create an array containing all the numbers you want (or whatever container your language uses) minus all the number you don't want and select at random from the array.

Upvotes: 0

Related Questions