r/dailyprogrammer • • Aug 11 '12

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

Write a function that calculates the [intersection](http://en.wikipedia.org/wiki/Intersection_(set_theory)) 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

View all comments

1

u/abraxas235_work Aug 13 '12 edited Aug 13 '12

Web based solution incoming!

PHP:

class rectangle {
	
	private $vertices;
	/*
	 * Element 0 = top left x coordinate
	 * Element 1 = top left y coordinate
	 * Element 2 = bottom right x coordinate
	 * Element 3 = bottom right y coordinate
	 */
	
	public function __construct($v) {
		$this->vertices = $v;
	}
	
	public function get_vertices(){
		return $this->vertices;
	}
	
	private function check_contain($v){
		if($v[0] >= $this->vertices[0] && $v[0] <= $this->vertices[2] 
			&& $v[1] >= $this->vertices[1] && $v[1] <= $this->vertices[3]){
			return true;
		}
		else if($v[2] >= $this->vertices[0] && $v[2] <= $this->vertices[2] 
			&& $v[3] >= $this->vertices[1] && $v[3] <= $this->vertices[3] ){
			return true;
		}
		else{
			return false;
		}
	}
	
	private function check_intersect($rectangle){
		if($this->check_contain($rectangle->get_vertices())
				|| $rectangle->check_contain($this->get_vertices())){
			return true;
		}
		else{
			return false;
		}
	}
	
	public function intersecting_rect($rectangle){
		if($this->check_intersect($rectangle)){
			$intersecting_rect[0] = max(array($this->vertices[0], $rectangle->get_vertices()[0]));  
			$intersecting_rect[1] = max(array($this->vertices[1], $rectangle->get_vertices()[1]));
			$intersecting_rect[2] = min(array($this->vertices[2], $rectangle->get_vertices()[2]));  
			$intersecting_rect[3] = min(array($this->vertices[3], $rectangle->get_vertices()[3]));
			
			return $intersecting_rect;
		}
		else{
			return "No intersection";
		}
	}
}