加入工作日迄今为止要考虑到周末和节假日考虑到、工作日、节假日、迄今为止

由网友(娇气的小奶包)分享简介:给出一个日期,和节假日列表,我怎么个工作日内给定数量添加到该日期?有很多的解决方案,以更小的问题,这没有考虑节假日的(参见例如添加天,以一个日期,但不包括周末的)。given a date, and a list of holidays, how do i add the given number of workda...

给出一个日期,和节假日列表,我怎么个工作日内给定数量添加到该日期?有很多的解决方案,以更小的问题,这没有考虑节假日的(参见例如添加天,以一个日期,但不包括周末的)。

given a date, and a list of holidays, how do i add the given number of workdays to this date? there are a lot of solutions to the smaller problem which does not take account of holidays (see for example Adding Days to a Date but Excluding Weekends).

编辑:我在寻找一个O(1),或至少是线性的(在节假日的数量)解决方案

i am looking for a O(1) or at least linear (on the number of holidays) solution.

请帮忙 谢谢 康斯坦丁

please help thanks konstantin

推荐答案

接近O(1)(不初始化时间)

如果你真的想要一个O(1)解决方案,我希望你不要考虑初始化FASE。

If you really want an O(1) solution, I hope you do not take into account the initialization fase.

要初始化:

内建可查询范围内的所有日期是有效的返回值排序列表。 (使用类似code从里克·加纳答案) 在构建哈希表与日期从上面的列表,日期为重点,指数在列表中值

初​​始化code,你只需要一次,您缓存的结果。

The initialization code, you need only once, and you cache the result.

要查询/计算

 List<DateTime> validWorkdays = // ;
 Dictionary<DateTime, int> lookupIndexOfValidWorkday = // ;

 DateTime AddWorkdays(DateTime start, int count) {
    var startIndex = lookupIndexOfValidWorkday[start];
    return validWorkDays[startIndex + count];
 }

关于从字典检索:

获取或设置该属性的值接近一个O(1)操作。

Getting or setting the value of this property approaches an O(1) operation.

O(n)的假期数量

根据这一假期的列表进行排序,从最旧到最新的假设。 (Credits平日公式)

Under the assumption that the list of holidays is sorted from oldest to newest. (Credits for weekdays formula)

DateTime AddBusinessDay(DateTime start, int count, IEnumerable<DateTime> holidays) {
   int daysToAdd = count + ((count/ 5) * 2) + ((((int)start.DayOfWeek + (count % 5)) >= 5) ? 2 : 0);
   var end = start.AddDays(daysToAdd);
   foreach(var dt in holidays) {
     if (dt >= start && dt <= end) {
        end = end.AddDays(1);
        if (end.DayOfWeek == DayOfWeek.Saterday) {
          end = end.AddDays(2);
        }
     }
   }
   return end;
}    

此方法可以被优化。

这是很难创建一个只计算结果,就像您链接到的问题的答案,一个简单的公式。因为当你调整假期,你需要考虑到新的假期,可能落入你的范围。在周末,你知道它们之间有一个固定的间隔。

It's very hard to create a simple formula that just calculates the result, like the answers in the question you linked to. Because when you adjust for holidays you need to take into account new holidays that might fall into your range. For weekends, you know there is a fixed interval between them.

阅读全文

相关推荐

最新文章