scala - Scala中的联合日期范围
问题描述
假设我有一个日期范围元组列表,那么组合和减少它们的最优雅和最有效的方法是什么?
例如,以下列表:
('2021-01-10', '2021-01-15')
('2021-01-13', '2021-01-17')
('2021-01-25', '2021-01-30')
('2021-01-17', '2021-01-20')
('2021-02-17', '2021-02-20')
输出应该是:
('2021-01-10','2021-01-20')
('2021-01-25','2021-01-30')
('2021-02-17', '2021-02-20')
谢谢
解决方案
这个怎么样?
type LIST = List[(String, String)]
def mergeDates(list: LIST): LIST = {
@annotation.tailrec
def loop(l: LIST, curr: (String, String), res: LIST): LIST =
l match {
case hd::tail =>
if (hd._1 <= curr._2) {
loop(tail, (curr._1, hd._2), res)
} else {
loop(tail, hd, curr +: res)
}
case _ =>
(curr +: res).reverse
}
list.sortBy(_._1) match {
case hd::tail => loop(tail, hd, Nil)
case _ => Nil
}
}
mergeDates(list).foreach(println)
这是有效的,因为这种格式的日期字符串按日期顺序正确排序。如果允许更通用的日期格式,则需要做更多的工作。
推荐阅读
- coldfusion - 尝试将base64转换为coldfsuion中的图像,但它显示为黑色图像
- xquery - 如何将映射变量传递给外部函数,如 eval 并在 marklogic xquery 中调用
- javascript - 错误:来自工作人员的未知操作:在 pdf.js 中的 Worker.MessageHandler._onComObjOnMessage 处未定义
- terraform - terraform 缺少资源实例键
- javascript - 这是我只需要 Id:1 数据。一些 Id 没有值,而一些 Id 有另一个值
- ruby-on-rails - 禁止某些参数在 Ruby on Rails 中登录
- rust - recusive trait 容器的不适当的生命周期
- ios - 如何在 iOS 上选择所有文件?
- dialogflow-es - 在 Dialogflow(内联编辑器)中部署的问题
- sql - 网上商店产品过滤器的 T-SQL 查询