Badr Hari
Badr Hari

Reputation: 8414

Random number that divides by 5

Random random = new Random();
int randomx = random.Next(0, 240);

This is the way I get my random number, from 0 to 240, how can get only integrals that divide with 5? (0 included)

0, 5, 10, 15, 20, 25 .. 240

Upvotes: 4

Views: 2050

Answers (4)

sehe
sehe

Reputation: 393389

In response to paxdiablo.

WARNING Humor code not very suitable for production environments

public  static IEnumerable<int> RandomGen(int minValue, int maxValue)
{
    var random = new Random();
    while (true) yield return random.Next(minValue, maxValue);
}

public static IEnumerable<int> RandomGen(int minValue, int maxValue, params Func<int, bool>[] predicates)
{
    return RandomGen(minValue, maxValue)
        .Where(rnd => predicates.Aggregate(true, (a, pred) => a && pred(rnd)));
}

This way you can simply

foreach (var x in RandomGen(0, 240, r => (r%5)==0))
{
// use x
}

(please don't shoot me)

Upvotes: 2

paxdiablo
paxdiablo

Reputation: 881893

Here's one (very bad, hence the community wiki) way to do it:

Random random = new Random();
int randomx = 1;
while ((randomx % 5) > 0)
    randomx = random.Next (0,240);

:-)

Feel free to downvote this answer into oblivion. It's really just to prevent others from posting it.

Upvotes: 7

marcind
marcind

Reputation: 53183

How about this:

Random random = new Random();
return random.Next(0, 48) * 5;

Or, if you need 240 included, as your list indicates:

Random random = new Random();
return random.Next(0, 49) * 5;

Upvotes: 19

Brian Ball
Brian Ball

Reputation: 12606

Random random = new Random();
int randomx = random.Next(0, 48) * 5;

Upvotes: 4

Related Questions