以亂數進行某段日期區間的抽樣

以亂數進行某段日期區間的抽樣

本文討論假設我們要依照下列條件亂數來進行抽樣,應該怎麼做:

    • 開始日期:2011-07-20
    • 結束日期:2011-07-30
    • 每天開始時間:08:00
    • 每天結束時間:09:00
    • 抽樣數量:10筆
    • 格式:yy-MM-dd hh:mm

 

  • 筆者將上述需求除格式外,寫成一個函式以利將來條件改變時得以reuse,程式碼如下:
   1:  /// <summary>
   2:  /// 亂數進行日期抽樣
   3:  /// </summary>
   4:  /// <param name="StartDate">起始日期</param>
   5:  /// <param name="DueDate">結束日期</param>
   6:  /// <param name="StartTime">每日起始時間</param>
   7:  /// <param name="DueTime">每日結束時間</param>
   8:  /// <param name="count">抽樣數量</param>
   9:  /// <returns></returns>
  10:  private static List<DateTime> GetRandomDate(DateTime StartDate, DateTime DueDate, int StartTime, int DueTime,int count)
  11:  {
  12:      List<DateTime> list = new List<DateTime>();
  13:      if (!(StartDate.CompareTo(DueDate) > 0 || StartTime.CompareTo(DueTime) > 0 || count < 0))
  14:      {
  15:          Random ran = new Random();
  16:          while (list.Count < count)
  17:          {
  18:              DateTime dtCurrent = StartDate.AddDays(ran.Next(0
  19:                                                          , int.Parse(DueDate.Subtract(StartDate).TotalDays.ToString()) - 1));
  20:              dtCurrent = dtCurrent.AddHours(StartTime).AddMinutes(ran.Next(0, ((DueTime - StartTime) * 60) - 1));
  21:              if (dtCurrent.Hour.CompareTo(DueTime) < 1)
  22:              {
  23:                  if (!list.Contains(dtCurrent))
  24:                  {
  25:                      list.Add(dtCurrent);
  26:                  }
  27:              }
  28:          }
  29:      }
  30:      return list;
  31:  }

  • 下列程式碼示範如何使用GetRandomDate函式:
   1:  static void Main(string[] args)
   2:  {
   3:      List<DateTime> list = GetRandomDate(new DateTime(2011, 7, 20), new DateTime(2011, 7, 30), 8, 9,10);
   4:      foreach (DateTime dt in list)
   5:      {
   6:          Console.WriteLine(string.Format("{0},{1}", list.Count.ToString(), dt.ToString("yy-MM-dd hh:mm")));
   7:      }   
   8:      Console.ReadKey();
   9:  }

 

  • 執行結果:

image