从TimeSpans列表中找到不同的TimeSpan持续时间

如何解决从TimeSpans列表中找到不同的TimeSpan持续时间

我在尝试处理TimeSpan对象列表时遇到了一些麻烦,而没有很多代码似乎仍然无法解决所有可能的情况,所以我想我已经有点代码/逻辑上的盲点了现在!

我有一个TimeSpans列表,其中可能会发生重叠,但是我需要一个TimeSpans列表,这些列表没有重叠,但要覆盖所有TimeSpans的整个持续时间。

例如(请注意,日期采用ddMMyyyy格式):

TS1: 01/01/2020 to 01/02/2020 (1 month)
TS2: 01/03/2020 to 01/05/2020 (2 months)
TS3: 01/04/2020 to 01/07/2020 (3 months with a 1 month overlap with TS2)
TS4: 01/10/2020 to 01/12/2020 (2 months)
TS5: 01/09/2020 to 01/01/2021 (4 months with a 2 month overlap with TS4)

因此,在这种情况下,我希望获得3个TimeSpans:

TSA: 01/01/2020 to 01/02/2020 (1 month - same as TS1 as there are no overlaps)
TSB: 01/03/2020 to 01/07/2020 (4 months - combination of TS2 and TS3)
TSC: 01/09/2020 to 01/01/2021 (4 months - combination of TS4 and TS5,technically only TS5 as TS4 is fully encompassed by TS5)

我尝试过在线研究算法,但是没有任何运气。

任何建议都将受到欢迎。

解决方法

这根本没有优化,但是 ememically 您可以通过添加块并查找重叠,然后合并这些重叠来完成此操作;像这样:

using System;
using System.Collections.Generic;
using System.Globalization;

static class P
{

    static void Main()
    {
        var results = new List<(DateTime From,DateTime To)>();

        Add("01/01/2020","01/02/2020");
        Add("01/03/2020","01/05/2020");
        Add("01/04/2020","01/07/2020");
        Add("01/10/2020","01/12/2020");
        Add("01/09/2020","01/01/2021");

        // SEE BELOW,IMPORTANT
        results.Sort(); // initial sort
        while (MergeOneOverlap()) { }
        foreach (var range in results)
        {
            Console.WriteLine($"{range.From:dd/MM/yyyy} - {range.To:dd/MM/yyyy}");
        }

        bool MergeOneOverlap()
        {
            for (int i = 0; i < results.Count; i++)
            {
                var x = results[i];
                for (int j = i + 1; j < results.Count; j++)
                {
                    var y = results[j];
                    if (x.Intersects(y))
                    {
                        results[i] = x.Merge(y);
                        results.RemoveAt(j);
                        results.Sort(); // retain sort while making progress
                        return true;
                    }
                }
            }
            return false;
        }
        void Add(string from,string to)
            => results.Add(
                (DateTime.ParseExact(from,"dd/MM/yyyy",CultureInfo.InvariantCulture),DateTime.ParseExact(to,CultureInfo.InvariantCulture)));
    }
    static bool ContainsInclusive(this (DateTime From,DateTime To) range,DateTime when)
    => when >= range.From && when <= range.To;

    static bool Intersects(this (DateTime From,DateTime To) x,(DateTime From,DateTime To) y)
        => x.ContainsInclusive(y.From) || x.ContainsInclusive(y.To) || y.ContainsInclusive(x.From) || y.ContainsInclusive(x.To);

    static (DateTime From,DateTime To) Merge(this (DateTime From,DateTime To) y)
        => (x.From < y.From ? x.From : y.From,x.To > y.To ? x.To : y.To);

}

如果这是用于大量数据,则必须考虑变得更加聪明,以避免O(N ^ 3)问题。 可能有助于合并每个添加项,如果这样做通常会使项目数量减少。

也有可能将复杂度降低到O(N ^ 2)并纯粹合并转发(即在成功合并时不要中断),但是我还没有运用足够的思想来了解其含义。而且O(N ^ 2)仍然很糟糕。

对于大数据,使用排序列表可能会有所帮助,因此您可以在开始日期进行二进制搜索以找到插入点。不过,这比我在这里写的要复杂。


我有95%的把握也可以,即O(N ^ 2):

        MergeOverlaps();
        foreach (var range in results)
        {
            Console.WriteLine($"{range.From:dd/MM/yyyy} - {range.To:dd/MM/yyyy}");
        }

        void MergeOverlaps()
        {
            results.Sort();
            for (int i = 0; i < results.Count; i++)
            {
                var x = results[i];
                for (int j = i + 1; j < results.Count; j++)
                {
                    var y = results[j];
                    if (x.Intersects(y))
                    {
                        results[i] = x = x.Merge(y);
                        results.RemoveAt(j--);
                    }
                }
            }
        }
,

我建议尝试使用蛮力搜索或深度优先搜索算法。

首先,您需要按开始日期对时间范围进行排序。

暴力力: 您可以尝试所有组合,并按重叠/不重叠对它们进行评分,并且您可能想对覆盖的总时间跨度进行评分。

深度优先搜索: 编写一个递归算法,该算法从添加第一个间隔开始,然后在出现重叠时添加更多的间隔和回溯。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


依赖报错 idea导入项目后依赖报错,解决方案:https://blog.csdn.net/weixin_42420249/article/details/81191861 依赖版本报错:更换其他版本 无法下载依赖可参考:https://blog.csdn.net/weixin_42628809/a
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下 2021-12-03 13:33:33.927 ERROR 7228 [ main] o.s.b.d.LoggingFailureAnalysisReporter : *************************** APPL
错误1:gradle项目控制台输出为乱码 # 解决方案:https://blog.csdn.net/weixin_43501566/article/details/112482302 # 在gradle-wrapper.properties 添加以下内容 org.gradle.jvmargs=-Df
错误还原:在查询的过程中,传入的workType为0时,该条件不起作用 &lt;select id=&quot;xxx&quot;&gt; SELECT di.id, di.name, di.work_type, di.updated... &lt;where&gt; &lt;if test=&qu
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct redisServer’没有名为‘server_cpulist’的成员 redisSetCpuAffinity(server.server_cpulist); ^ server.c: 在函数‘hasActiveC
解决方案1 1、改项目中.idea/workspace.xml配置文件,增加dynamic.classpath参数 2、搜索PropertiesComponent,添加如下 &lt;property name=&quot;dynamic.classpath&quot; value=&quot;tru
删除根组件app.vue中的默认代码后报错:Module Error (from ./node_modules/eslint-loader/index.js): 解决方案:关闭ESlint代码检测,在项目根目录创建vue.config.js,在文件中添加 module.exports = { lin
查看spark默认的python版本 [root@master day27]# pyspark /home/software/spark-2.3.4-bin-hadoop2.7/conf/spark-env.sh: line 2: /usr/local/hadoop/bin/hadoop: No s
使用本地python环境可以成功执行 import pandas as pd import matplotlib.pyplot as plt # 设置字体 plt.rcParams[&#39;font.sans-serif&#39;] = [&#39;SimHei&#39;] # 能正确显示负号 p
错误1:Request method ‘DELETE‘ not supported 错误还原:controller层有一个接口,访问该接口时报错:Request method ‘DELETE‘ not supported 错误原因:没有接收到前端传入的参数,修改为如下 参考 错误2:cannot r
错误1:启动docker镜像时报错:Error response from daemon: driver failed programming external connectivity on endpoint quirky_allen 解决方法:重启docker -&gt; systemctl r
错误1:private field ‘xxx‘ is never assigned 按Altʾnter快捷键,选择第2项 参考:https://blog.csdn.net/shi_hong_fei_hei/article/details/88814070 错误2:启动时报错,不能找到主启动类 #
报错如下,通过源不能下载,最后警告pip需升级版本 Requirement already satisfied: pip in c:\users\ychen\appdata\local\programs\python\python310\lib\site-packages (22.0.4) Coll
错误1:maven打包报错 错误还原:使用maven打包项目时报错如下 [ERROR] Failed to execute goal org.apache.maven.plugins:maven-resources-plugin:3.2.0:resources (default-resources)
错误1:服务调用时报错 服务消费者模块assess通过openFeign调用服务提供者模块hires 如下为服务提供者模块hires的控制层接口 @RestController @RequestMapping(&quot;/hires&quot;) public class FeignControl
错误1:运行项目后报如下错误 解决方案 报错2:Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.8.1:compile (default-compile) on project sb 解决方案:在pom.
参考 错误原因 过滤器或拦截器在生效时,redisTemplate还没有注入 解决方案:在注入容器时就生效 @Component //项目运行时就注入Spring容器 public class RedisBean { @Resource private RedisTemplate&lt;String
使用vite构建项目报错 C:\Users\ychen\work&gt;npm init @vitejs/app @vitejs/create-app is deprecated, use npm init vite instead C:\Users\ychen\AppData\Local\npm-