gpt4 book ai didi

arrays - 在 ruby​​ 数组中查找并展平重叠的时间间隔

转载 作者:塔克拉玛干 更新时间:2023-11-03 06:17:50 26 4
gpt4 key购买 nike

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

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"] }

最佳答案

我理解 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])

关于arrays - 在 ruby​​ 数组中查找并展平重叠的时间间隔,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38466692/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com