Reputation: 531
I create a random Time randomTime
between two TimeSpans using
Random random = new Random();
TimeSpan start = TimeSpan.FromHours(StundenS);
TimeSpan end = TimeSpan.FromHours(StundenE);
int maxMinutes = (int)((end - start).TotalMinutes);
int minutes = random.Next(maxMinutes);
TimeSpan randomTime = start.Add(TimeSpan.FromMinutes(minutes));
If StundenS
= 10
and StundenE
= 11
, the result could be 10:51
, which is correct. Yet how do I make it change in 5 minute increments instead of 1 minute increment, so 10:51
is forbidden, 10:50
is not and 10:55
is not either?
EDIT: I solved it with
minutes = (int)(Math.Round((double)minutes / 5) * 5);
TimeSpan randomTime = start.Add(TimeSpan.FromMinutes(minutes));
Upvotes: 3
Views: 2809
Reputation: 39
You could give the random.Next an array which consists of increments of 5s.
int[] array = new int {5,10,15,...,55};
int minutes = random.Next(0, array.Length);
int randomnumber = array[minutes];
Upvotes: 0
Reputation: 61359
Reduce your range and multiply.
It is very easy to get a random integer between two values (say, 0 and 10). In such a case 10 discrete values are possible outcomes.
Now that I can only get one of 10 numbers, I can multiply to get the correct scale. So to get any multiple of 10 from 0 to 100 I could write:
int rand = random.Next(0, 10);
int scaledRand = rand * 10;
If I then wanted values between 50 and 150 (still that 100 range notice) you simply add:
int finalRand = scaledRand + 50;
Similarly, you have a range of 60 with multiples of 5. Dividing gives a requirement of 12 discrete values so the code:
int rand = random.Next(0, 12);
int scaledRand = rand * 5;
Gives you the multiples you want.
Upvotes: 5