计算嵌套数组中的更改

时间:2018-02-22 03:28:04

标签: arrays ruby count

此阵列中显示警报的状态。 时间格式如下: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"]]

我想算一下次数" red"之后是"绿色"在10秒的时间内。

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

3 个答案:

答案 0 :(得分:1)

#!/usr/bin/env ruby

A = [
  ["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"]
]


def seconds(string) # hh:mm:ss
  hours, minutes, seconds = string.split(':').map(&:to_i)
  hours * 60 * 60 + minutes * 60 + seconds
end


def seconds_diff_relative_to_next(array, i)
  seconds(array[i+1].last) - seconds(array[i].last)
end


reds_and_greens = A.select { |a| a.first == 'red' || a.first == 'green' }
puts "Reds and greens:\n\n"
p reds_and_greens; puts;


matches = (0..(reds_and_greens.size - 2)).select do |i|
  if reds_and_greens[i].first == 'red' && reds_and_greens[i+1].first == 'green'
    seconds = seconds_diff_relative_to_next(reds_and_greens, i)
    puts "#{i}, red -> green, difference in seconds = #{seconds}"
    seconds <= 10
  end
end


puts
matches.each do |match|
  puts "Match: #{match}: #{reds_and_greens[match..match+1].inspect}"
end


=begin

Produces:

Reds and greens:

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

0, red -> green, difference in seconds = 5
2, red -> green, difference in seconds = 20
4, red -> green, difference in seconds = 1

Match: 0: [["red", "00:00:00"], ["green", "00:00:05"]]
Match: 4: [["red", "00:00:28"], ["green", "00:00:29"]]

=end

答案 1 :(得分:1)

Initialize...
Connecting to ws://localhost:8080/ws/logs/43ba7a2a-8fac-4ebb-8a8f-e046e5534944...
Connected!

 --- x11vnc loop: 1 ---

2018/02/22 05:20:47 Loading configuration files...
2018/02/22 05:20:47 Loaded configuration from [/etc/selenoid/browsers.json]
2018/02/22 05:20:47 Using default containers log configuration because of:read error: open config/container-logs.json: no such file or directory
2018/02/22 05:20:47 Timezone: UTC
2018/02/22 05:20:47 Listening on :4444
2018/02/22 05:20:47 [NEW_REQUEST]
2018/02/22 05:20:47 [NEW_REQUEST_ACCEPTED]
2018/02/22 05:20:47 [0] [LOCATING_SERVICE] [firefox-57.0]
2018/02/22 05:20:47 [0] [USING_DRIVER] [firefox-57.0]
2018/02/22 05:20:47 [0] [ALLOCATING_PORT]
2018/02/22 05:20:47 [0] [ALLOCATED_PORT] [41809]
2018/02/22 05:20:47 [0] [STARTING_PROCESS] [[/usr/bin/geckodriver --host :: --log debug --port=41809]]
1519276847981   geckodriver     INFO    geckodriver 0.19.1
1519276847981   webdriver::httpapi      DEBUG   Creating routes
1519276847986   geckodriver     INFO    Listening on [::]:41809
1519276848032   webdriver::server       DEBUG   -> HEAD /
1519276848160   webdriver::server       DEBUG   <- 404 Not Found {"value":{"error":"unknown command","message":"HEAD / did not match a known command","stacktrace":"stack backtrace:\n   0:           0x4edb3c - backtrace::backtrace::trace::hc4bd56a2f176de7e\n   1:           0x4edb72 - backtrace::capture::Backtrace::new::he3b2a15d39027c46\n   2:           0x440ac8 - webdriver::error::WebDriverError::new::ha0fbd6d1a1131b43\n   3:           0x43a665 - <webdriver::server::HttpHandler<U> as hyper::server::Handler>::handle::h343049f2e1aa3f13\n   4:           0x404b4d - std::sys_common::backtrace::__rust_begin_short_backtrace::he840f14c79c8e321\n   5:           0x40bee6 - std::panicking::try::do_call::hdd1d6b985699ef9d\n   6:           0x5e6a6c - panic_unwind::__rust_maybe_catch_panic\n                        at /checkout/src/libpanic_unwind/lib.rs:99\n   7:           0x41ef02 - <F as alloc::boxed::FnBox<A>>::call_box::hae8ac6ade91dedb6\n   8:           0x5df13b - alloc::boxed::{{impl}}::call_once<(),()>\n                        at /checkout/src/liballoc/boxed.rs:692\n                         - std::sys_common::thread::start_thread\n                        at /checkout/src/libstd/sys_common/thread.rs:21\n                         - std::sys::imp::thread::{{impl}}::new::thread_start\n                        at /checkout/src/libstd/sys/unix/thread.rs:84"}}
2018/02/22 05:20:48 [0] [PROCESS_STARTED] [32] [181.491408ms]
2018/02/22 05:20:48 [0] [PROXYING_REQUESTS] [http://127.0.0.1:41809]
2018/02/22 05:20:48 [0] [SESSION_ATTEMPTED] [unknown] [http://127.0.0.1:41809] [1]
1519276848161   webdriver::server       DEBUG   -> POST /session {"desiredCapabilities":{"browserName":"firefox","javascriptEnabled":true,"acceptSslCerts":true,"platform":"ANY","moz:firefoxOptions":{"log":{"level":"trace"}},"version":"57.0","name":"Test / Login"}}
1519276848167   mozrunner::runner       INFO    Running command: "/usr/bin/firefox" "-marionette" "-profile" "/tmp/rust_mozprofile.i3MIoxBzkGAM"
1519276848171   geckodriver::marionette TRACE     connection attempt 0/600
1519276848271   geckodriver::marionette TRACE     connection attempt 1/600
 --- x11vnc loop: waiting for: 61

1519276848372   geckodriver::marionette TRACE     connection attempt 2/600
PORT=5900
1519276848474   geckodriver::marionette TRACE     connection attempt 3/600
1519276848575   geckodriver::marionette TRACE     connection attempt 4/600
1519276848677   geckodriver::marionette TRACE     connection attempt 5/600
1519276848694   Marionette      DEBUG   Received observer notification "profile-after-change"
1519276848755   Marionette      DEBUG   Received observer notification "command-line-startup"
1519276848756   Marionette      INFO    Enabled via --marionette
1519276848778   geckodriver::marionette TRACE     connection attempt 6/600
1519276848880   geckodriver::marionette TRACE     connection attempt 7/600
1519276848980   geckodriver::marionette TRACE     connection attempt 8/600
1519276849081   geckodriver::marionette TRACE     connection attempt 9/600
1519276849183   geckodriver::marionette TRACE     connection attempt 10/600
1519276849285   geckodriver::marionette TRACE     connection attempt 11/600
1519276849386   geckodriver::marionette TRACE     connection attempt 12/600
1519276849487   geckodriver::marionette TRACE     connection attempt 13/600
1519276849589   geckodriver::marionette TRACE     connection attempt 14/600
1519276849690   geckodriver::marionette TRACE     connection attempt 15/600
1519276849792   geckodriver::marionette TRACE     connection attempt 16/600
1519276849894   geckodriver::marionette TRACE     connection attempt 17/600
1519276849930   Marionette      DEBUG   Received observer notification "sessionstore-windows-restored"
1519276849996   geckodriver::marionette TRACE     connection attempt 18/600
1519276850097   geckodriver::marionette TRACE     connection attempt 19/600
1519276850197   geckodriver::marionette TRACE     connection attempt 20/600
1519276850298   geckodriver::marionette TRACE     connection attempt 21/600
1519276850399   geckodriver::marionette TRACE     connection attempt 22/600
1519276850499   geckodriver::marionette TRACE     connection attempt 23/600
1519276850600   geckodriver::marionette TRACE     connection attempt 24/600
1519276850679   Marionette      DEBUG   Setting recommended pref toolkit.cosmeticAnimations.enabled to false
1519276850681   Marionette      DEBUG   Setting recommended pref datareporting.policy.dataSubmissionPolicyAccepted to false
1519276850681   Marionette      DEBUG   Setting recommended pref extensions.e10sBlocksEnabling to false
1519276850682   Marionette      DEBUG   New connections are accepted
1519276850683   Marionette      INFO    Listening on port 37569
1519276850702   geckodriver::marionette DEBUG   Connected to Marionette onlocalhost:37569
1519276850712   Marionette      DEBUG   Accepted connection 0 from 127.0.0.1:42836
1519276850714   geckodriver::marionette TRACE   <- {"applicationType":"gecko","marionetteProtocol":3}
1519276850714   geckodriver::marionette TRACE   -> 315:[0,1,"newSession",{"acceptSslCerts":true,"browserName":"firefox","capabilities":{"desiredCapabilities":{"acceptSslCerts":true,"browserName":"firefox","javascriptEnabled":true,"name":"Test / Login","platform":"ANY","version":"57.0"}},"javascriptEnabled":true,"name":"Test / Login","platform":"ANY","version":"57.0"}]
1519276850717   Marionette      TRACE   0 -> [0,1,"newSession",{"acceptSslCerts":true,"browserName":"firefox","capabilities":{"desiredCapabilities":{"acceptSslCerts":true,"browserName":"firefox","javascriptEnabled":true,"name":"Test / Login","platform":"ANY","version":"57.0"}},"javascriptEnabled":true,"name":"Test / Login","platform":"ANY","version":"57.0"}]
1519276850783   Marionette      DEBUG   Register listener.js for window 2147483649
1519276850806   Marionette      TRACE   0 <- [1,1,null,{"sessionId":"43ba7a2a-8fac-4ebb-8a8f-e046e5534944","capabilities":{"browserName":"firefox","browserVersion":"57.0","platformName":"linux","platformVersion":"4.9.60-linuxkit-aufs","pageLoadStrategy":"normal","acceptInsecureCerts":false,"timeouts":{"implicit":0,"pageLoad":300000,"script":30000},"rotatable":false,"moz:accessibilityChecks":false,"moz:headless":false,"moz:processID":37,"moz:profile":"/tmp/rust_mozprofile.i3MIoxBzkGAM","moz:webdriverClick":false}}]
1519276850809   geckodriver::marionette TRACE   <- [1,1,null,{"sessionId":"43ba7a2a-8fac-4ebb-8a8f-e046e5534944","capabilities":{"browserName":"firefox","browserVersion":"57.0","platformName":"linux","platformVersion":"4.9.60-linuxkit-aufs","pageLoadStrategy":"normal","acceptInsecureCerts":false,"timeouts":{"implicit":0,"pageLoad":300000,"script":30000},"rotatable":false,"moz:accessibilityChecks":false,"moz:headless":false,"moz:processID":37,"moz:profile":"/tmp/rust_mozprofile.i3MIoxBzkGAM","moz:webdriverClick":false}}]
1519276850809   webdriver::server       DEBUG   <- 200 OK {"value": {"sessionId":"43ba7a2a-8fac-4ebb-8a8f-e046e5534944","capabilities":{"acceptInsecureCerts":false,"browserName":"firefox","browserVersion":"57.0","moz:accessibilityChecks":false,"moz:headless":false,"moz:processID":37,"moz:profile":"/tmp/rust_mozprofile.i3MIoxBzkGAM","moz:webdriverClick":false,"pageLoadStrategy":"normal","platformName":"linux","platformVersion":"4.9.60-linuxkit-aufs","rotatable":false,"timeouts":{"implicit":0,"pageLoad":300000,"script":30000}}}}
2018/02/22 05:20:50 [0] [SESSION_CREATED] [unknown] [43ba7a2a-8fac-4ebb-8a8f-e046e5534944] [http://127.0.0.1:41809] [1] [2.832759113s]
2018/02/22 05:21:50 [SESSION_DELETED] [43ba7a2a-8fac-4ebb-8a8f-e046e5534944]
1519276910817   webdriver::server       DEBUG   -> DELETE /session/43ba7a2a-8fac-4ebb-8a8f-e046e5534944
1519276910819   geckodriver::marionette TRACE   -> 37:[0,2,"quit",{"flags":["eForceQuit"]}]
1519276910827   Marionette      TRACE   0 -> [0,2,"quit",{"flags":["eForceQuit"]}]
1519276910830   Marionette      DEBUG   New connections will no longer be accepted
1519276910973   Marionette      TRACE   0 <- [1,2,null,{"cause":"shutdown"}]
1519276911015   geckodriver::marionette TRACE   <- [1,2,null,{"cause":"shutdown"}]
1519276911015   webdriver::server       DEBUG   Deleting session
1519276911015   geckodriver::marionette DEBUG   Stopping browser process
1519276911077   webdriver::server       DEBUG   <- 200 OK {"value": {}}
2018/02/22 05:21:51 [0] [TERMINATING_PROCESS] [32]
2018/02/22 05:21:51 [0] [TERMINATED_PROCESS] [32]
Disconnected

答案 2 :(得分:0)

以下是您遇到问题的解决方案

array = [
  ["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"]
]

# iterating over first to second last element of array. Skipping the last element because we want to compare every element with its successor.

selected_result_set = array[0..-2].select.with_index do |arr, index|
  # first comparing if current element (array) contains 'red' and its successor contains 'green'
  if arr[0] == 'red' && array[index + 1][0] == 'green'
    # comparing time difference here
    (DateTime.parse(arr[1]).to_time - DateTime.parse(array[index + 1][1]).to_time) <= 10
  end
end

# selected result will consist of the array of 'red' value which passes our condition
selected_result_set.count

希望这有帮助