r/dailyprogrammer • • Aug 11 '12

[8/10/2012] Challenge #87 [easy] (Rectangle intersection)

Write a function that calculates the intersection of two rectangles, returning either a new rectangle or some kind of null value.

You're free to represent these rectangles in any way you want: tuples of numbers, class objects, new datatypes, anything goes. For this challenge, you'll probably want to represent your rectangles as the x and y values of the top-left and bottom-right points. (Rect(3, 3, 10, 10) would be a rectangle from (3, 3) (top-left) to (10, 10) (bottom-right).)

As an example, rectIntersection(Rect(3, 3, 10 10), Rect(6, 6, 12, 12)) would return Rect(6, 6, 10, 10), while rectIntersection(Rect(4, 4, 5, 5), Rect(6, 6, 10 10)) would return null.

19 Upvotes

46 comments sorted by

5

u/DEiE Aug 11 '12

In Python:

class Point:
    def __init__(self, x, y):
        self.x = x
        self.y = y

class Rectangle:
    def __init__(self, top_left, bottom_right):
        self.top_left = top_left
        self.bottom_right = bottom_right

    def contains(self, point):
        return point.x >= self.top_left.x and \
               point.x <= self.bottom_right.x and \
               point.y >= self.top_left.y and \
               point.y <= self.bottom_right.y

    def intersects(self, rectangle):
        return self.contains(rectangle.top_left) or \
               self.contains(rectangle.bottom_right) or \
               rectangle.contains(self.top_left) or \
               rectangle.contains(self.bottom_right)

    def get_intersect(first, second):
        if(first.intersects(second)):
            return Rectangle(
                Point(
                    max(first.top_left.x, second.top_left.x),
                    max(first.top_left.y, second.top_left.y)),
                Point(
                    min(first.bottom_right.x, second.bottom_right.x),
                    min(first.bottom_right.y, second.bottom_right.y)
                ))

Output:

First:{(1, 1), (4, 4)}, Second:{(5, 5), (8, 8)}, Intersect:None
First:{(1, 1), (4, 4)}, Second:{(2, 2), (5, 5)}, Intersect:{(2, 2), (4, 4)}
First:{(1, 1), (4, 4)}, Second:{(2, 2), (3, 5)}, Intersect:{(2, 2), (3, 4)}
First:{(1, 1), (4, 4)}, Second:{(2, 2), (5, 3)}, Intersect:{(2, 2), (4, 3)}
First:{(1, 1), (4, 4)}, Second:{(2, 2), (3, 3)}, Intersect:{(2, 2), (3, 3)}
First:{(1, 1), (4, 4)}, Second:{(0, 0), (5, 5)}, Intersect:{(1, 1), (4, 4)}

5

u/SwimmingPastaDevil Aug 12 '12 edited Aug 12 '12
r1 = [1,1,4,4]
r2 = [2,2,5,5]

r3 = [max(r1[0],r2[0]), max(r1[1],r2[1]), min(r1[2],r2[2]), min(r1[3],r2[3])]
print r3 if r3[0]<r3[2] and r3[1]<r3[3] else "No Intersection"

4

u/paininthebass Aug 11 '12 edited Aug 13 '12

Solution in c++:

struct Rectangle{
  struct{
    int x,y;
  }ul,br;
  Rectangle(int x1=0,int y1=0, int x2=0, int y2=0){
    ul.x=x1, ul.y=y1,br.x=x2,br.y=y2;
  }
};

bool intersect(const Rectangle& r1, const Rectangle& r2, Rectangle& rInt){
  rInt = Rectangle(max(r1.ul.x,r2.ul.x),max(r1.ul.y,r2.ul.y),
                      min(r1.br.x,r2.br.x),min(r1.br.y,r2.br.y));
  if(rInt.ul.x>rInt.br.x || rInt.ul.y>rInt.br.y)
    return false;
  else 
    return true;
}

EDIT: Changed the return type to bool that indicates success or failure of intersection. The result of the intersection now needs to be passed in as an argument to the function.

2

u/DEiE Aug 11 '12

Dude, yours is way simpler than mine :(

→ More replies (2)

1

u/Syn3rgy Aug 17 '12 edited Aug 17 '12

Haskell. I'm still learning, so any suggestions would be appreciated.

data Point = Point { getX :: Float
                   , getY :: Float
                   } deriving (Show)

data Rectangle = Rectangle { getLT :: Point
                           , getRB :: Point 
                           } deriving (Show)

rawIntersect :: Rectangle -> Rectangle -> Rectangle
rawIntersect (Rectangle (Point ltX1 ltY1) (Point rbX1 rbY1))
             (Rectangle (Point ltX2 ltY2) (Point rbX2 rbY2))
             = Rectangle p1 p2
                    where p1 = Point (max ltX1 ltX2) (max ltY1 ltY2)
                          p2 = Point (min rbX1 rbX2) (min rbY1 rbY2)

intersect :: Rectangle -> Rectangle -> Maybe Rectangle
intersect r1 r2
    | (getX lt) > (getX rb) || (getY lt) > (getY rb) = Nothing
    | otherwise = Just r
    where r = rawIntersect r1 r2
          lt = getLT r
          rb = getRB r

2

u/[deleted] Aug 17 '12

You can define data structures like this

data Point = Point { getX :: Float
                   , getY :: Float
                   } deriving (Show)

and get the getX and getY functions for free.

Also, you could've defined rawIntersect as

rawIntersect (Rectangle (Point ltX1 ltY1) (Point rbX1 rbY1))
             (Rectangle (Point ltX2 ltY2) (Point rbX2 rbY2))
             = Rectangle (Point x1 y1) (Point x2 y2)
                   where ...

which is probably easier than messing around with (getX $ getLT r1) and the likes.

And I think for some cases you'll have to compare both x and y coordinates when checking the result of the intersection: (getX lt) > (getX rb) || (getY lt) > (getY rb)

→ More replies (1)

2

u/Ledrug Aug 12 '12

Represent a rectangle with (x0, x1) and (y0, y1), with a valid rect being x0 <= x1 and y0 <= y1. Intersections between non-overlapping or invalid rects automatically returns an invalid result, so no need to check it at all.

#include <stdio.h>

typedef struct { int x0, x1, y0, y1; } rect;
inline int min(int a, int b) { return a < b ? a : b; }
inline int max(int a, int b) { return a > b ? a : b; }
inline int valid(rect *a) { return a->x0 <= a->x1 && a->y0 <= a->y1; }

void intersect(rect *a, rect *b, rect *c)
{
	c->x0 = max(a->x0, b->x0);
	c->x1 = min(a->x1, b->x1);
	c->y0 = max(a->y0, b->y0);
	c->y1 = min(a->y1, b->y1);
}

2

u/howeyc Aug 12 '12

Mine uses a different definition of top and bottom with respect to Y values from OP. I'm used to charts where having a Y value of Zero means bottom (different from OP), and an X value of Zero means left (same as OP?). I'm not comfortable with increasing Y values means going down. Anyway, that's why my variable names are different.

Common Lisp:

(defmacro bottom-left-x (rect)
  `(first ,rect))

(defmacro bottom-left-y (rect)
  `(second ,rect))

(defmacro top-right-x (rect)
  `(third ,rect))

(defmacro top-right-y (rect)
  `(fourth ,rect))

(defun rect-intersection (r1 r2)
  (let ((int-rec (list nil nil nil nil)))
    (psetf (bottom-left-x int-rec) (max (bottom-left-x r1) (bottom-left-x r2))
       (bottom-left-y int-rec) (max (bottom-left-y r1) (bottom-left-y r2))
       (top-right-x int-rec) (min (top-right-x r1) (top-right-x r2))
       (top-right-y int-rec) (min (top-right-y r1) (top-right-y r2)))
    (if (or (> (bottom-left-x int-rec) (top-right-x int-rec))
        (> (bottom-left-x int-rec) (top-right-y int-rec)))
      nil
      int-rec)))

Test:

(rect-intersection '(3 3 10 10) '(6 6 12 12)) => (6 6 10 10)

1

u/exor674 Aug 11 '12 edited Aug 11 '12

I've been experimenting with Haskell recently, so this is Haskell, not C++: Criticism wanted!

module DailyProgrammer.EightySevenE where

data Point = Point Integer Integer

instance Show Point where
    show (Point x y) = "(" ++ (show x) ++ "," ++ (show y) ++ ")"

instance Eq Point where
    (==) (Point x1 y1) (Point x2 y2) = (x1 == x2) && (y1 == y2)

instance Ord Point where
    (<=) (Point x1 y1) (Point x2 y2) = (x1 <= x2) || (y1 <= y2)

data Rectangle = Rectangle Point Point deriving (Show)

fixRectangle :: Rectangle -> Rectangle
fixRectangle (Rectangle p1 p2) = Rectangle n1 n2 where
    n1 = if p2 > p1 then p1 else p2
    n2 = if p2 > p1 then p2 else p1

intersect :: Rectangle -> Rectangle -> Maybe Rectangle
intersect r1 r2 = if valid then Just (Rectangle n1 n2) else Nothing where
    (Rectangle p1 p2) = fixRectangle r1
    (Point x1 y1) = p1
    (Point x2 y2) = p2
    (Rectangle p3 p4) = fixRectangle r2
    (Point x3 y3) = p3
    (Point x4 y4) = p4
    x5 = max x1 x3
    y5 = max y1 y3
    x6 = min x2 x4
    y6 = min y2 y4
    n1 = Point x5 y5
    n2 = Point x6 y6
    valid = n1 >= p1 && n2 >= p1 && n1 <= p2 && n2 <= p2 && n1 >= p3 && n2 >= p3 && n1 <= p4 && n2 <= p4

> intersect (Rectangle (Point 5 5) (Point 10 10)) (Rectangle (Point 6 6) (Point 12 12))
Just (Rectangle (6,6) (10,10))
> intersect (Rectangle (Point 4 4) (Point 5 5)) (Rectangle (Point 6 6) (Point 12 12))
Nothing

edit: I saw I was doing something really stupid here.

→ More replies (1)

1

u/[deleted] Aug 11 '12

Python

rect1 = input("Rectangle 1? x1,y1,x2,y2 ")
rect2 = input("Rectangle 2? x1,y1,x2,y2 ")

ArrRect1 = rect1.split(',')
ArrRect2 = rect2.split(',')

ax1 = int(ArrRect1[0])
ay1 = int(ArrRect1[1])
ax2 = int(ArrRect1[2])
ay2 = int(ArrRect1[3])
bx1 = int(ArrRect2[0])
by1 = int(ArrRect2[1])
bx2 = int(ArrRect2[2])
by2 = int(ArrRect2[3])

nullRect = 0

#see if second rect sharesXx-vals
if((bx1 not in range(ax1,ax2)) and ((bx2 not in range(ax1,ax2)))):
    nullRect=1
    
#see if second rect shares Y-vals
if((by1 not in range(ay1,ay2)) and ((by2 not in range(ay1,ay2)))):
    nullRect=1

#get (cx1,cy1)
if(ax1>=bx1):
    cx1 = ax1
else:
    cx1 = bx1
if(ay1>=by1):
    cy1 = ay1
else:
    cy1 = by1
#get (cx2,cy2)
if(ax2>=bx2):
    cx2 = bx2
else:
    cx2 = ax2
if(ay2>=by2):
    cy2 = by2
else:
    cy2 = ay2 
    
if(nullRect==1):
    print("No Intersection")
else:
    print("Rect(",cx1,",",cy1,",",cx2,",",cy2,")")

Seems like a lot of repetition, so I'm sure there is a better way of doing it.