Created
December 5, 2016 19:26
-
-
Save mrdougwright/17d11e75855d40e414a4efd213793fdc to your computer and use it in GitHub Desktop.
rectangular intersection
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# write an algorithm to find the intersection of two users' love rectangles. | |
def intersection(rectangle1, rectangle2) | |
rect_hash1 = calc_space(rectangle1) | |
rect_hash2 = calc_space(rectangle2) | |
intersect_hash = overlap(rect_hash1, rect_hash2) | |
convert_to_rectangle(intersect_hash) | |
end | |
def calc_space(rectangle) | |
rect_hash = {} | |
rect_length_arr = [rectangle['left_x']] * rectangle['width'] | |
rect_length_arr.each_with_index do |_, i| | |
rect_length_arr[i] += i | |
end | |
rectangle['height'].times do |i| | |
rect_hash[rectangle['bottom_y'] + i] = rect_length_arr | |
end | |
rect_hash | |
end | |
def overlap(rect_hash1, rect_hash2) | |
new_rect_hash = {} | |
(rect_hash1.keys & rect_hash2.keys).each do |key| | |
new_rect_hash[key] = rect_hash1[key] & rect_hash2[key] | |
end | |
new_rect_hash | |
end | |
def convert_to_rectangle(intersect_hash) | |
rectangle_intersect = {} | |
width_indeces = intersect_hash.values | |
height_indeces = intersect_hash.keys | |
if width_indeces.empty? || height_indeces.empty? | |
return "No intersection." | |
end | |
rectangle_intersect['left_x'] = width_indeces[0].min | |
rectangle_intersect['bottom_y'] = height_indeces.min | |
rectangle_intersect['width'] = width_indeces[0].count | |
rectangle_intersect['height'] = height_indeces.count | |
rectangle_intersect | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment