gpt4 book ai didi

ruby - 在 Ruby 中查找周期和范围集差异的有效方法

转载 作者:数据小太阳 更新时间:2023-10-29 06:59:54 24 4
gpt4 key购买 nike

我在 Ruby 中有很多时间范围:

period = Time.parse('8:00am')..Time.parse('8:00pm')
incidents = [
Time.parse('7:00am')..Time.parse('9:00am'),
Time.parse('1:00pm')..Time.parse('3:00pm'),
Time.parse('1:30pm')..Time.parse('3:30pm'),
Time.parse('7:00pm')..Time.parse('9:00pm'),
]

我正试图在这段时间内获得一系列无事件 block 。对于以上内容:

[
Time.parse('9:00am')..Time.parse('1:00pm')
Time.parse('3:30pm')..Time.parse('7:00pm')
]

从上面可以看出,事件有可能重叠或延伸到时间段之外。范围内是否存在任何操作或类似的东西可以使这种计算更简单?

最佳答案

可能的解决方案

使用这个 range operator gem ,此脚本将(几乎)返回您想要的内容。

它以period开始,一个接一个地减去每个incident

由于从另一个范围中减去一个范围可能会产生两个范围,脚本实际上以 [period] 开头并在迭代之间保留一个自由事件范围数组:

require 'range_operators'

incident_free = incidents.inject([period]) do |free_ranges, incident|
free_ranges.flat_map do |free_range|
free_range - incident
end
end

p incident_free
#=> [2016-12-22 09:00:01 +0100..2016-12-22 12:59:59 +0100, 2016-12-22 15:30:01 +0100..2016-12-22 18:59:59 +0100]

注意事项

它提示 Time#succ 已过时。您可以添加

class Time
def succ
self+1
end
end

删除弃用警告,或使用 Gemfile :

gem 'range_operators', :git => 'https://github.com/monocle/range_operators.git'

安装更新版本的 gem,修复了 Time

脚本以 1 秒的分辨率工作,第一个范围从 09:00:01 开始,因为在 09:00:00 之前发生了事件。

关于ruby - 在 Ruby 中查找周期和范围集差异的有效方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41289502/

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