How can I generate the time of day, for example 23:55 or 17:30, just to not be generated from 00:00 to 05:30? 4th digit will be only 5 or 0
- More precisely, like this: take a random number from 67 to 286, inclusive, divide by 12 - it will be hours, take the remainder of the division by 12 and multiply by 5 - it will be minutes - andreymal
- not easier to take a random number from 535 (05: 3X) to 235 (23: 5X), and X randomly 0 or 5? - Andrey Ivasko
- @AndreyIvasko is not easier, because it can turn out 05:95 - andreymal
|
2 answers
Maybe use TimeSpan ? One of the designers takes hours, minutes and seconds. They then randomly through Random as necessary.
var ts = new TimeSpan(rnd.Next(0, 6), rnd.Next(0,55)/5*5, 0); Console.WriteLine($"{ts.Hours}:{ts.Minutes}")
- 1)
rnd.Next(0,55)
needs to be changed tornd.Next(0,60)
, otherwise 55 minutes will never come. 2) The task is time until 5:30, and in your case it may be five to seven. 3) In the case of a time limit of 5:30, one small nuisance appears: the probability of obtaining any value in the interval from 5:00 to 5:30 is higher than in other intervals. - John - 1. Yes, I made a mistake with the boundary values. 2. Yeah, inattention) - Alexander Li
- Did you carefully read the question? However, the author probably didn’t go too much either;)
00:00 - 05:30
- forbidden range - MBo - @MBo. Carefully. The author for some reason changes the question after each answer. - Alexander Lee
- @ Alexander Lee Strange, I looked at the edits, but there it is not reflected - MBo
|
The previous answer is incorrect. Thanks, @John!
Let's go otherwise. You must specify a time in the range from 00:00 to 05:30 in increments of 5 minutes. The total number of segments in 5 minutes = 5 * 12 + 6 = 66 segments. Then randomly generate a number from 0 to 66. Multiply it by 5. And create a TimeSpan with this number as minutes.
var parts = rnd.Next(0, 66); var minutes = parts * 5; var ts = new TimeSpan(0, minutes, 0); Console.WriteLine($"{ts.Hours}:{ts.Minutes}");
If you need a range excluding the time from 00:00 to 05:30, then you just need to make a shift and change the maximum random number.
//222 - кол-во 5-минутных отрезков в диапазоне от 5:30 до 00:00 var parts = rnd.Next(0, 222); // прибавляем сдвиг var minutes = parts * 5 + 66 * 5; var ts = new TimeSpan(0, minutes, 0); Console.WriteLine($"{ts.Hours}:{ts.Minutes}");
|