Find a line to cut two squares in half

Given two squares on a two dimensional plane, find a line that would cut these two squares in half.

My initial thoughts:
The straight line that connects the two centers of the two squares will cut both of them into half.

My initial codes:

	public class Square {
		private double topLeftX;
		private double topLeftY;
		private double edge;

		public Square(double topLeftX, double topLeftY, double edge) {
			super();
			this.topLeftX = topLeftX;
			this.topLeftY = topLeftY;
			this.edge = edge;
		}

		Pair<Double> getCenter() {
			return new Pair<Double>(topLeftX + edge / 2, topLeftY - edge / 2);
		}
	}

	public class Line {
		private double slope;
		private double intercept;

		public Line(double slope, double intercept) {
			super();
			this.slope = slope;
			this.intercept = intercept;
		}
	}

	public static Line getLine(Square a, Square b) {
		Pair<Double> centerA = a.getCenter();
		Pair<Double> centerB = b.getCenter();

		if (centerA.equals(centerB)) {
			return new Line(centerA.getY() / centerA.getX(), 0);
		} else {
			double slope = (centerB.getY() - centerA.getY())
					/ (centerB.getX() - centerA.getX());
			double intercept = (centerB.getX() * centerA.getY() - centerA
					.getX() * centerB.getY())
					/ (centerB.getX() - centerA.getX());
			return new Line(slope, intercept);
		}
	}

Solution:

	public class Square {
		public double left;
		public double top;
		public double bottom;
		public double right;

		public Square(double left, double top, double size) {
			this.left = left;
			this.top = top;
			this.bottom = top + size;
			this.right = left + size;
		}

		public Point middle() {
			return new Point((this.left + this.right) / 2,

			(this.top + this.bottom) / 2);
		}

		public Line cut(Square other) {
			Point middle_s = this.middle();
			Point middle_t = other.middle();
			if (middle_s == middle_t) {
				return new Line(new Point(left, top), new Point(right, bottom));
			} else {
				return new Line(middle_s, middle_t);
			}
		}
	}
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: