Random number divisible by 5

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

So I get my random number, from 0 to 240, how can I get only integrals that are divisible by 5? (Including 0)

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

+3
source share
4 answers

How about this:

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

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

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

Here is one (very bad, therefore wiki community) way to do this:

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

:-)

Feel free to omit this answer. It is really easy for others not to publish it.

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

paxdiablo.

,

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)));
}

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

(, )

+2

Source: https://habr.com/ru/post/1787604/


All Articles