Skip to content

Instantly share code, notes, and snippets.

Created May 10, 2016 03:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save anonymous/dc9823fda8fcd8ed4e6e3573efadcc71 to your computer and use it in GitHub Desktop.
Save anonymous/dc9823fda8fcd8ed4e6e3573efadcc71 to your computer and use it in GitHub Desktop.
https://repl.it/BrIc/230 created by anonymous
# Write a function, `rec_intersection(rect1, rect2)` and returns the
# intersection of the two.
#
# Rectangles are represented as a pair of coordinate-pairs: the
# bottom-left and top-right coordinates (given in `[x, y]` notation).
#
# Hint: You can calculate the left-most x coordinate of the
# intersection by taking the maximum of the left-most x coordinate of
# each rectangle. Likewise, you can calculate the top-most y
# coordinate of the intersection by taking the minimum of the top most
# y coordinate of each rectangle.
#
# Difficulty: 4/5
def rec_intersection(rect1, rect2)
result = nil
conjunction_react = conjunction_react(rect1,rect2)
if conjunction_react[0][0] < conjunction_react[1][0]
result = conjunction_react
end
return result
end
def conjunction_react(rect1,rect2)
rect = []
if rect1[0][0] > rect2[0][0]
p1_x = rect1[0][0]
else
p1_x = rect2[0][0]
end
if rect1[0][1] > rect2[0][1]
p1_y = rect1[0][1]
else
p1_y = rect2[0][1]
end
if rect1[1][0] < rect2[1][0]
p2_x = rect1[1][0]
else
p2_x = rect2[1][0]
end
if rect1[1][1] < rect2[1][1]
p2_y = rect1[1][1]
else
p2_y = rect2[1][1]
end
p1 = [p1_x,p1_y]
p2 = [p2_x,p2_y]
rect = [p1,p2]
return rect
end
puts("\nTests for #rec_intersection")
puts("===============================================")
puts "rec_intersection([[0, 0], [2, 1]], [[1, 0], [3, 1]]) == [[1, 0], [2, 1]]: " + (rec_intersection([[0, 0], [2, 1]], [[1, 0], [3, 1]]) == [[1, 0], [2, 1]]).to_s
puts "rec_intersection([[1, 1], [2, 2]], [[0, 0], [5, 5]]) == [[1, 1], [2, 2]]: " + (rec_intersection([[1, 1], [2, 2]], [[0, 0], [5, 5]]) == [[1, 1], [2, 2]]).to_s
puts "rec_intersection([[1, 1], [2, 2]], [[4, 4], [5, 5]]) == nil: " + (rec_intersection([[1, 1], [2, 2]], [[4, 4], [5, 5]]) == nil).to_s
puts "rec_intersection([[1, 1], [5, 4]], [[2, 2], [3, 5]]) == [[2, 2], [3, 4]]: " + (rec_intersection([[1, 1], [5, 4]], [[2, 2], [3, 5]]) == [[2, 2], [3, 4]]).to_s
puts("===============================================")
ruby 2.2.0p0 (2014-12-25 revision 49005)
>>>
Tests for #rec_intersection
===============================================
rec_intersection([[0, 0], [2, 1]], [[1, 0], [3, 1]]) == [[1, 0], [2, 1]]: true
rec_intersection([[1, 1], [2, 2]], [[0, 0], [5, 5]]) == [[1, 1], [2, 2]]: true
rec_intersection([[1, 1], [2, 2]], [[4, 4], [5, 5]]) == nil: true
rec_intersection([[1, 1], [5, 4]], [[2, 2], [3, 5]]) == [[2, 2], [3, 4]]: true
===============================================
=> nil
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment