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?
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.
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.
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:
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With