11 March 2014

题目:

面试题#给定平面上的两个格点P1(x1,y1),P2(x2,y2),在线段P1P2上,除P1、P2外,一共有多少个格点?格点定义为x和y都是整数的点。关注微信公众账号“待字闺中”,了解和讨论参考分析。

分析: 常规思路:从一个点开始,X坐标逐渐往另一个点以1的距离靠近,然后计算一下对应的每个Y坐标是不是整数。

好思路:暂时没想到。。。。。。。


Java代码实现

package auguest;

import java.util.ArrayList;
import java.util.List;

public class GetPoints {

    /**
     * @param args
     * #面试题#给定平面上的两个格点P1(x1,y1)P2(x2,y2),在线段P1P2上,除P1P2外,一共有多少个格点?格点定义为xy都是整数的点。
     */
    public static void main(String[] args) {
        Point point1 = new Point(-30, -30);
        Point point2 = new Point(31, 31);

        List<Point> points = getPoints(point1, point2);
        for (Point point : points) {
            System.out.println(point);
        }

    }

    public static List<Point> getPoints(Point point1, Point point2) {
        List<Point> points = new ArrayList<Point>();

        int lengthX = point2.getX() - point1.getX();
        int lengthY = point2.getY() - point1.getY();

        if (lengthX == 0) {
            for (int i=1; i<lengthY; i++) {
                Point p = new Point(point1.getX(), point1.getY()+i);
                points.add(p);
            }
        } else if (lengthY == 0) {
            for (int i=1; i<lengthX; i++) {
                Point p = new Point(point1.getX()+1, point1.getY());
                points.add(p);
            }
        } else {
            for (int i=1; i<lengthX; i++) {
                int tmpX = point1.getX() + i;
                int tmpY = tmpX * lengthY % lengthX;
                if (tmpY == 0) {
                    points.add(new Point(tmpX, tmpX * lengthY / lengthX));
                }
            }
        }

        return points;
    }

}


class Point {
    private int x;
    private int y;

    public Point() {
        x = 0;
        y = 0;
    }

    public Point(int x, int y) {
        this.x = x;
        this.y = y;
    }

    public int getX() {
        return x;
    }

    public void setX(int x) {
        this.x = x;
    }

    public int getY() {
        return y;
    }

    public void setY(int y) {
        this.y = y;
    }

    @Override
    public String toString() {
        return "Point: x=" + this.x + ", y=" + this.y;
    }

}

</div>