Ruby on rails Ruby,时间间隔用于时间数组

Ruby on rails Ruby,时间间隔用于时间数组,ruby-on-rails,ruby,Ruby On Rails,Ruby,我有一个查询(对于MongoDB数据库),它返回已映射的对象,这些对象每15分钟报告一次,但问题是,如果说其中一台服务器出现严重错误,那么这段时间将无法解释 以该阵列为例: [ {:timestamp=>2011-09-26 19:00:00 UTC, :count=>318}, {:timestamp=>2011-09-26 19:15:00 UTC, :count=>308}, {:timestamp=>2011-09-26 19:30:00 UTC

我有一个查询(对于MongoDB数据库),它返回已映射的对象,这些对象每15分钟报告一次,但问题是,如果说其中一台服务器出现严重错误,那么这段时间将无法解释

以该阵列为例:

[
  {:timestamp=>2011-09-26 19:00:00 UTC, :count=>318},
  {:timestamp=>2011-09-26 19:15:00 UTC, :count=>308},
  {:timestamp=>2011-09-26 19:30:00 UTC, :count=>222},
  {:timestamp=>2011-09-26 19:45:00 UTC, :count=>215},
  {:timestamp=>2011-09-26 20:00:00 UTC, :count=>166},
  {:timestamp=>2011-09-26 21:15:00 UTC, :count=>149},
  {:timestamp=>2011-09-26 21:30:00 UTC, :count=>145},
  {:timestamp=>2011-09-26 21:45:00 UTC, :count=>107},
  {:timestamp=>2011-09-26 22:00:00 UTC, :count=>137},
  {:timestamp=>2011-09-26 22:15:00 UTC, :count=>135},
  {:timestamp=>2011-09-26 22:30:00 UTC, :count=>191},
  {:timestamp=>2011-09-26 22:45:00 UTC, :count=>235}
]
您会注意到时间范围中缺少时间:

{:timestamp=>2011-09-26 20:15:00 UTC},
{:timestamp=>2011-09-26 20:30:00 UTC},
{:timestamp=>2011-09-26 20:45:00 UTC},
{:timestamp=>2011-09-26 21:00:00 UTC}
我如何才能将顶部作为输入,并推断出那些将是丢失的行?时间增量总是15分钟,它实际上是一个真正的日期对象,而不是那样的字符串

我只是无法想象如何迭代这个


任何帮助都将不胜感激。

只需从第一个时间戳开始,然后递增15分钟,验证该条目是否存在,然后继续进行,直到到达最后一个时间戳。

我能想到的最简单的方法是按时间戳对数组排序,然后执行以下操作:

missing_times = []
reports.each_with_index do |report, index|
  if reports[index + 1]
    if report.timestamp.advance(minutes: 15) < report[index + 1].timestamp
      i = 0
      while(report.timestamp.advance(minutes: 15*i) < report[index+1].timestamp)
        missing_times << report.timestamp.advance(minutes: 15*i)
      end
    end
  end
end
missing_times=[]
报告。每个带有索引的|报告,索引|
如果报告[索引+1]
if report.timestamp.advance(分钟数:15)缺少_times而不是在循环中执行多个循环,若您以15分钟为增量创建一个总时间跨度数组,并仅与您的报告集进行比较并删除任何匹配项,那个么使用大型数据集将更有效

start_time = report.first
span = ((report.last - start_time)/60/15).to_i   # this gives the number of 15min blocks
test_array = []
span.times do |i|
  test_array << start_time + i*15.minutes
end
report.each do |r|
  test_array.delete(r)   # or in your case, r.timestamp
end
start\u time=report.first
span=((report.last-start_time)/60/15)。to_i#这给出了15分钟的块数
测试_数组=[]
span.times do|i|

当间隔大于15分钟时,test_array My answer only循环,如果没有间隔,我的解决方案只在数组上迭代一次。而且,我的阵列不会在所有可能的时间循环,只会在填补空白的时间循环。您的解决方案将始终有2个循环,一个用于加载时间跨度,另一个用于循环所有元素。当没有间隙时,您的解决方案将在所有元素上循环两次。我最坏的情况下,总是在所有可用增量上循环一次,等于
span.times
loop另外,test_array.delete在数组本身上迭代以查找要删除的元素,请参见代码:,因此您的代码是O(n^2),因为每次调用delete,您可能会在整个阵列上循环。我在执行时遇到一些问题,在
if report[:timestamp].advance(分钟数:15)
报告[index+1]
行中,就在小于等于零之后?当我把它改为
reports[index+1]
时,我认为它的外观会永远保持不变。思想?