user1943020
user1943020

Reputation:

How can I generate a random number that is one of the set [ 0,5,10,15]?

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

Answers (7)

Kong
Kong

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

Dejan Ciev
Dejan Ciev

Reputation: 142

  Random r = new Random();
  var a = r.Next(4)*5;

Upvotes: 0

AgentFire
AgentFire

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

syclee
syclee

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

Mike Precup
Mike Precup

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

Parimal Raj
Parimal Raj

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

TGH
TGH

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

Related Questions