Skip to content

Instantly share code, notes, and snippets.

@marvinahv
Created October 6, 2020 23:36
Show Gist options
  • Save marvinahv/6e2501590b47e6c8808cd3b889c5655e to your computer and use it in GitHub Desktop.
Save marvinahv/6e2501590b47e6c8808cd3b889c5655e to your computer and use it in GitHub Desktop.
Finished example
class Line
attr_accessor :startpoint
attr_accessor :endpoint
def initialize(startpoint, endpoint)
@startpoint = startpoint
@endpoint = endpoint
end
def to_s
"(#{@startpoint}, #{@endpoint})"
end
end
# Return an array of merged Lines
#
def merge_lines(lines)
current_line = nil
merged_lines = []
# (1, 5), (2, 6), (6, 10), (15, 20), (17, 21)
# (1, 10), (15, 21)
lines.each_with_index do |line, index|
# line (1, 10)
if current_line.nil?
current_line = Line.new(line.startpoint, line.endpoint)
else
# current_line = (15, 21)
# line
#
if line.endpoint > current_line.endpoint
endpoint = line.endpoint
current_line = Line.new(current_line.startpoint, endpoint)
end
end
# 15, 21
next_line = lines[index+1]
if next_line
if next_line.startpoint > current_line.endpoint
merged_lines << current_line
current_line = nil
end
else
merged_lines << current_line
end
end
pp merged_lines
merged_lines
end
example1 = [
Line.new(1, 5),
Line.new(2, 6),
Line.new(6, 10),
Line.new(15, 20),
Line.new(17, 21)
]
example2 = [
Line.new(1, 10),
Line.new(15, 21)
]
example3 = [
Line.new(1, 5),
Line.new(2, 3),
Line.new(4, 8),
Line.new(8, 10)
]
merge_lines(example1)
merge_lines(example2)
merge_lines(example3)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment