コード例 #1
0
ファイル: Square.java プロジェクト: 0x0all/ctci
  public Line cut(Square other) {
    /* Calculate where a line between each middle would collide with the edges of the squares */
    Point p1 = extend(this.middle(), other.middle(), this.size);
    Point p2 = extend(this.middle(), other.middle(), -1 * this.size);
    Point p3 = extend(other.middle(), this.middle(), other.size);
    Point p4 = extend(other.middle(), this.middle(), -1 * other.size);

    /* Of above points, find start and end of lines. Start is farthest left (with top most as a tie breaker)
     * and end is farthest right (with bottom most as a tie breaker */
    Point start = p1;
    Point end = p1;
    Point[] points = {p2, p3, p4};
    for (int i = 0; i < points.length; i++) {
      if (points[i].x < start.x || (points[i].x == start.x && points[i].y < start.y)) {
        start = points[i];
      } else if (points[i].x > end.x || (points[i].x == end.x && points[i].y > end.y)) {
        end = points[i];
      }
    }

    return new Line(start, end);
  }