We have two lists, a list of events each with an id, a start_time, and a start_time_rage. The start_time_range puts a tolerance around start_time to find near misses.
The objective is to filter the current_matches, to only include those that appear in the previous matches. An item "appears" in the list if the id matches and the start_time is within the range.
To achieve this, I have this loop, but with our ever increasing data size it is becoming very slow. I need to optimise it:
current_matches.select! do |match_row|
previous_matches_collection.any? do |previous_match|
previous_match[:item_id] == match_row[:item_id] &&
previous_match[:start_time_range].include?(match_row[:start_time].to_f)
end
end
If it were just the item_id I needed I could do this:
previous_ids = previous_matches_collection.collect{|i| i[:item_id] }
current_matches.select! do |match_row|
previous_ids.include?(match_row[:item_id])
end
But I can't see a way of using that approach while matching the time condition in each item.
In terms of data, current_matches could be 300 and previous_matches_collection could be 1k+. Is there a way of doing this without iterating through 300,000 combinations?
edit - Sample data:
previous_matches_collection = [
{ item_id: 1, start_time: 1597094395.1195982, start_time_range: (1597094393.6195982..1597094396.6195982) },
{ item_id: 1, start_time: 1597095083.116646, start_time_range: (1597095081.616646..1597095084.616646) },
{ item_id: 1, start_time: 1597095403.028223, start_time_range: (1597095401.528223..1597095404.528223) },
{ item_id: 2, start_time: 1597098035.056944, start_time_range: (1597098033.556944..1597098036.556944) },
{ item_id: 3, start_time: 1597096073.4109557, start_time_range: (1597096071.9109557..1597096074.9109557) },
{ item_id: 4, start_time: 1597094785.6987526, start_time_range: (1597094784.1987526..1597094787.1987526) },
{ item_id: 4, start_time: 1597098077.41271, start_time_range: (1597098075.91271..1597098078.91271) }
]
current_matches = [
{ item_id: 1, start_time: 1597094395.9195982 },
{ item_id: 1, start_time: 1597095085.116646, },
{ item_id: 1, start_time: 1597095404.228223, },
{ item_id: 2, start_time: 1597094395.1195982 },
{ item_id: 4, start_time: 1597094395.1195982 },
{ item_id: 6, start_time: 1597094395.1195982 },
{ item_id: 17, start_time: 1597094395.1195982 }
]