Skip to content

Instantly share code, notes, and snippets.

@pandwoter
Last active April 19, 2022 08:58
Show Gist options
  • Save pandwoter/57e25a89d388046ecf1d0877ecb1d48f to your computer and use it in GitHub Desktop.
Save pandwoter/57e25a89d388046ecf1d0877ecb1d48f to your computer and use it in GitHub Desktop.
MERGE TIMES
require 'date'
# task input
input = [['10:00', '10:20'],
['10:40', '11:00'],
['10:50', '12:00'],
['12:00', '13:00'],
['10:00', '10:20']]
class TimeConverter
class << self
def call(time)
DateTime.parse("3rd Feb 2001 #{time}:06").to_time.to_i
end
def unpack(timestamp)
time = DateTime.strptime(timestamp.to_s,'%s')
"#{time.hour}:#{time.minute}"
end
end
end
class Solution
attr_reader :input_array,
:first_element,
:array_length
def initialize(input)
@input_array = input.map { |ar| ar.map { |time| TimeConverter.call(time) } }.sort
@array_length = input_array.size
@first_element = input_array[0]
end
def call
base = first_element.dup
res = []
input_array[1..].each.with_index do |interval, idx|
min, max = base[0], base[1]
min_cur, max_cur = interval[0], interval[1]
if max >= min_cur && max_cur > max || max_cur == max
base = [min, max_cur]
elsif max >= min_cur && max_cur < max
elsif min_cur > max
res << base
base = [min_cur, max_cur]
else
res << interval
end
if idx == (array_length - 2)
res << base
end
end
res.map { |n| n.map { |n_a| TimeConverter.unpack(n_a) } }
end
end
p Solution.new(input).call
@pandwoter
Copy link
Author

test_case2 = [
[95, 123],
[100, 110],
[200, 300],
[300, 700]
]

test_case1 = [
[100, 200],
[400, 500],
[400, 700],
[800, 900],
[900, 1200],
[1500, 1800]
]

test_case3 = [
[1000, 1020],
[1040, 1100],
[1050, 1200],
[1200, 1300],
[1000, 1020]
]

test_case = [
[100, 200],
[150, 170],
[200, 250],
[220, 290],
[1000, 1020]
]

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment