Reputation:
I have been using the following:
Random r = new Random();
var a = r.Next(9)
To generate a random number between 0-9.
However now I need to generate one of the following numbers at random: 0,5,10,15
Is there a way that I could modify this just to select the numbers above?
Upvotes: 0
Views: 142
Reputation: 9576
Generate a random number between 0 and 3, then simply use that as an index into an array:
Something like this (pseudocode):
var nums = [0, 5, 10, 15];
return nums[new Random().Next(4)];
Or if it really is as simple as multiples of 5; simple multiply it:
return new Random().Next(4) * 5;
Upvotes: 1
Reputation: 9780
public static IEnumerable<int> Range(int count, int start = 0, int step = 1)
{
for (int i = start; i < count; i++)
yield return i;
}
var arr = Range(4, 0, 5).ToArray(); // 0, 5, 10, 15.
Upvotes: 0
Reputation: 697
const int iterator = 5;
const int upperBound = 15;
var possibleValues = (from n in Enumerable.Range(0, upperBound + 1)
where n % iterator == 0
select n).ToArray();
Random r = new Random();
var a = possibleValues[r.Next(possibleValues.Length)];
Upvotes: 0
Reputation: 4218
Random r = new Random();
var a = r.Next(4) * 5;
Will do the trick. Note that the argument is an exclusive upper bound, so it won't ever be generated. Your code sample generates between 0 and 8.
If you need a different set of numbers, you could do the following:
int[] possible = new int[] { 0, 5, 10, 15 };
Random r = new Random();
int a = possible[r.Next(possible.length)];
Upvotes: 6
Reputation: 20585
Random rnd = new Random();
//create a pre-defined list
int[] nums = new int[] {0, 5, 10, 15};
int rndNum = nums[rnd.Next(nums.Length)];
You can even repeate the loop to generate more then one random number from the set of per-defined numbers in an array.
Upvotes: 4
Reputation: 39268
Yes. Put the four numbers into an array of four elements. Then generate random numbers between 0-3 and use that to index the array
Upvotes: 1