Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

random

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?

like image 984
tenthplanet0 Avatar asked Aug 28 '13 09:08

tenthplanet0


People also ask

How do I generate random integers within a specific range in Java?

Generate Random Number Using the Random Class in Java The Random class of Java can generate a random integer within the specified range by using the nextInt() method, which returns an integer value.

How do you do range math random?

random() function is used to return a floating-point pseudo-random number between range [0,1) , 0 (inclusive) and 1 (exclusive). This random number can then be scaled according to the desired range. Syntax: Math.


2 Answers

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.
like image 138
Bridge Avatar answered Sep 21 '22 23:09

Bridge


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.

like image 39
Voicu Avatar answered Sep 24 '22 23:09

Voicu