【问题标题】:Union date ranges in ScalaScala中的联合日期范围
【发布时间】:2021-10-19 07:27:56
【问题描述】:

假设我有一个日期范围元组的列表,那么组合和减少它们的最优雅和最有效的方法是什么?

例如以下列表:

('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')

谢谢

【问题讨论】:

    标签: scala functional-programming


    【解决方案1】:

    这个怎么样?

    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)
    

    之所以有效,是因为这种格式的日期字符串按日期顺序正确排序。如果允许更通用的日期格式,则需要做更多的工作。

    【讨论】:

    • 我认为这很完美。谢谢
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-01-07
    • 2018-09-02
    • 1970-01-01
    • 2015-06-19
    • 1970-01-01
    • 1970-01-01
    • 2014-12-16
    相关资源
    最近更新 更多