计算嵌套数组中的更改 [英] Counting changes in a nested array

查看:48
本文介绍了计算嵌套数组中的更改的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

警报状态在此阵列中显示。
时间格式如下:HH:MM:SS

The status of an alarm is shown in this array. Time format is as follows HH:MM:SS

[["red",    "00:00:00"],
 ["orange", "00:00:02"],
 ["green",  "00:00:05"],
 ["red",    "00:00:07"],
 ["green",  "00:00:27"],
 ["red",    "00:00:28"],
 ["green",  "00:00:29"]]

我要计算次数在10秒钟内,红色后面紧跟着绿色。

I would like to count the number of times "red" is followed by "green" within a time period of 10 seconds.

Step 1: Look for red

Step 2: IF Not last item 
           Compare with next item on array
        ELSE Go to Step 4  

Step 3: IF green, 
           time_difference = green_time - red_time 
           IF time_difference <= 10 seconds
                    count = count + 1
                    Go to Step 1
           ELSE Go to Step 1
         ELSE Go to Step 2

Step 4: Print Count

计数应为2

推荐答案

result =
  input.map do |k, t|
    [k, DateTime.parse(t)]
  end.each_with_object(prev: nil, count: 0) do |(k, t), acc|
    case k
                  # keep the time of the previous occurrence of "red" 
    when "red" then acc[:prev] = t    
    when "green" 
                        # seconds 
      acc[:count] += 1 if 24.0 * 60 * 60 * (t - acc[:prev]) < 10
      acc[:prev] = nil  
    end  
  end[:count]

  p(result)
  #⇒ 2

这篇关于计算嵌套数组中的更改的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆