Area of overlapping rectangles
Write a function that takes two rectangles and returns the area of the overlap. Sometimes the overlap is zero!
(overlap-area [{:top-left {:x 0 :y 0}
:bottom-right {:x 10 :y 10}}
{:top-left {:x 5 :y 5}
:bottom-right {:x 15 :y 15}}]) ;=> 25
;; 2 identical rectangles
(overlap-area [{:top-left {:x 0 :y 0}
:bottom-right {:x 1 :y 1}}
{:top-left {:x 0 :y 0}
:bottom-right {:x 1 :y 1}}]) ;=> 25
;; no overlap
(overlap-area [{:top-left {:x 0 :y 0}
:bottom-right {:x 1 :y 1}}
{:top-left {:x 6 :y 6}
:bottom-right {:x 8 :y 8}}]) ;=> 0
;; enclosing rectangles
(overlap-area [{:top-left {:x 0 :y 0}
:bottom-right {:x 1 :y 1}}
{:top-left {:x -1 :y -1}
:bottom-right {:x 2 :y 2}}]) ;=> 1
Thanks to this site for the challenge idea where it is considered Very Hard in JavaScript.
Please submit your solutions as comments on this gist.
@sztamas @steffan-westcott and @mainej, nice multi-rectangle enabled solutions!
@sztamas and @steffan-westcott that is really nice insight, using the natural ordering of :top-left and :bottom-right together with the use of
merge-with
to keep track of the smallest common rectangles, for a super compact solution - I wish I had though of that 👍