【问题标题】:Find and flatten overlapping time intervals in ruby array在 ruby​​ 数组中查找并展平重叠的时间间隔
【发布时间】:2016-11-22 19:55:37
【问题描述】:

我正在尝试为应用程序进行一些停机时间计算。我所拥有的是一个巨大的哈希数组,显示应用程序的不同部分何时关闭。散列包括开始时间和结束时间。问题是其中一些停机时间可能重叠。如何遍历哈希数组并找到重叠的时间间隔。

times = [{"timefrom"=>1461693247, "timeto"=>1461693307},
         {"timefrom"=>1462363987, "timeto"=>1462364607},
         {"timefrom"=>1462364037, "timeto"=>1462366037}]

例如,给定上面的数组,times[1] 和 times[2] 重叠。因此,理想情况下,我想做的是合并它们,以便它们形成一次长时间的中断。 IE。

times[1] = { "timefrom" => times[1]["timefrom"], "timeto" => times[2]["timeto"] }

【问题讨论】:

  • 可能有超过 2 个时间片重叠?输入是否按"timefrom" 排序?
  • @mudasobwa 理论上它们都可以重叠。超级不可能,但他们可以。是的,按timefrom排序
  • 欢迎来到 Stack Overflow。我们希望看到您为解决问题所做的努力。没有它,您似乎是在要求我们为您编写代码。请阅读“How to Ask”,包括链接页面。 meta.stackoverflow.com/q/261592/128421 也有助于阅读。
  • 您在解决此问题时遇到的 Ruby 问题是什么?

标签: arrays ruby algorithm time


【解决方案1】:

我了解times 的元素g(哈希)按g["timefrom"] 排序。

def combine_times(times)
  times[1..-1].each_with_object([times.first]) do |g,a|
    if g["timefrom"] < a.last["timeto"]
      a[-1]["timeto"] = [ a[-1]["timeto"], g["timeto"] ].max
    else
      a << g
    end
  end
end

times = [{"timefrom"=>1461693247, "timeto"=>1461693307},

         {"timefrom"=>1462363987, "timeto"=>1462364607},
         {"timefrom"=>1462364037, "timeto"=>1462366037}]

行间距显示times 的元素应该如何分组。

combine_times(times)
  #=> [{"timefrom"=>1461693247, "timeto"=>1461693307}, (times[0])
  #    {"timefrom"=>1462363987, "timeto"=>1462366037}] (combines times[1..2])

另一个例子:

times = [{"timefrom"=>10, "timeto"=>20},
         {"timefrom"=>12, "timeto"=>15},

         {"timefrom"=>22, "timeto"=>30},
         {"timefrom"=>28, "timeto"=>32},
         {"timefrom"=>29, "timeto"=>29},

         {"timefrom"=>32, "timeto"=>40},

         {"timefrom"=>42, "timeto"=>50},
         {"timefrom"=>43, "timeto"=>46}]

combine_times(times)
  #=> [{"timefrom"=>10, "timeto"=>20}, (combines times[0..1])
  #    {"timefrom"=>22, "timeto"=>32}, (combines times[2..4])
  #    {"timefrom"=>32, "timeto"=>40}, (times[5])
  #    {"timefrom"=>42, "timeto"=>50}] (combines times[6..7])

【讨论】:

  • 不错!按照您的解决方案,我能够改进我正在研究的 perl 解决方案。
猜你喜欢
  • 2014-02-23
  • 2023-01-10
  • 2021-09-25
  • 2021-03-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多