zoukankan      html  css  js  c++  java
  • c# 一个关于时间截断的算法取巧

    场景如下:

    在某一段时间内(有规律,以一个星期为最大区间),从一个时间区间中排除另外一个或者多个时间区间后,返回时间区间集合。

    举例如下:

    //时间区间:2018-02-01~2018-02-07
    //待排除时间区间集合:2018-02-03~2018-02-04,2018-02-06~2018-02-06   

    设计算法如下:

    public class myclass
    {
        public DateTime BeginDate { get; set; }
    
        public DateTime EndDate { get; set; }
    
        public List<myclass> SpCalc(List<myclass> list)
        {
            int Cnt = (EndDate - BeginDate).Days + 1;
            bool[] _temp = new bool[Cnt];
            Action<int, int, bool> _calc = (bIndex, eIndex, v) =>
                {
                    for (int i = bIndex; i <= eIndex; i++)
                    {
                        _temp[i] = v;
                    }
                };
            //初始化,全部置为true
            _calc(0, Cnt, true);
            //需要排除的时间段全部置为false
            list.ForEach(q => _calc((q.BeginDate - BeginDate).Days, (q.EndDate - BeginDate).Days, false));
            var resList = new List<myclass>();
            //遍历获取有效时间段
            int index = 0, start = -1;
            while (index < Cnt)
            {
                if (_temp[index])
                {
                    if (start == -1)
                        start = index;
                    if (index == 6)
                        resList.Add(new myclass()
                        {
                            BeginDate = BeginDate.AddDays(start),
                            EndDate = BeginDate.AddDays(index)
                        });
                }
                else
                {
                    if (start != -1)
                        resList.Add(new my()
                        {
                            BeginDate = BeginDate.AddDays(start),
                            EndDate = BeginDate.AddDays(index - 1)
                        });
                    start = -1;
                }
                index++;
            }
            return resList;
        }
    }
  • 相关阅读:
    Uva 10282 Babelfish
    Uva 10340 All in All
    Uva 11218 KTV
    Uva 193 Graph Coloring
    Uva 141 The Spot Game
    Uva 140 Bandwidth
    C#操作注册表(转)
    定位网站目录的各个符号的含义
    asp.net中错误:"The state information is invalid for this page and might be corrupted."
    用JavaScript获取客户端MAC地址(转)
  • 原文地址:https://www.cnblogs.com/lcawen/p/8663400.html
Copyright © 2011-2022 走看看