天天看點

電子圍欄核心代碼了解與測試(待完善)

一、核心代碼了解

boolean result = false;
            int i = 0;

            for (int j = this.points.length - 1; i < this.points.length; j = i++) {

                if (this.points[i].y > test.y != this.points[j].y > test.y//判斷test點在給定資料兩點中間
                        && test.x < (this.points[j].x - this.points[i].x) //給定兩點橫向距離
                        * (test.y - this.points[i].y) / (this.points[j].y - this.points[i].y) + this.points[i].x)
                        //測試點縱向距離與給定兩點縱向距離
                        //前後兩者相乘就是測試點到給定i點的橫向距離
                         {
                    result = !result;//點在範圍内
                }
            }

            return result;      

二、代碼如下

public class TTest70 {
    /**
     * 電子圍欄
     *
     * @param args
     */
    public static void main(String[] args) {

//        BoundaryPoint boundaryPoint = new BoundaryPoint(1.01, 20.02);
//        BoundaryPoint boundaryPoint1 = new BoundaryPoint(5.01, 6.02);
//        BoundaryPoint boundaryPoint2 = new BoundaryPoint(6.01, 6.02);
//        BoundaryPoint boundaryPoint3 = new BoundaryPoint(10.01, 20.02);
        BoundaryPoint boundaryPoint = new BoundaryPoint(1, 1);
        BoundaryPoint boundaryPoint1 = new BoundaryPoint(9, 9);
        BoundaryPoint boundaryPoint2 = new BoundaryPoint(4, 0.5);

        BoundaryPoint[] boundaryPoints = new BoundaryPoint[]{boundaryPoint,boundaryPoint1,boundaryPoint2};

        Boundary boundary = new Boundary(boundaryPoints);

        BoundaryPoint boundaryPoint4 = new BoundaryPoint(6, 1);
        boolean contains = boundary.contains(boundaryPoint4);
        System.out.println(contains);

    }

    static class BoundaryPoint {
        public final double x;
        public final double y;

        public BoundaryPoint(double x, double y) {
            this.x = x;
            this.y = y;
        }
    }
    static class Boundary {
        private final BoundaryPoint[] points;

        Boundary(BoundaryPoint[] points) {
            this.points = points;
        }

        boolean contains(BoundaryPoint test) {
            boolean result = false;
            int i = 0;

            for (int j = this.points.length - 1; i < this.points.length; j = i++) {

                if (this.points[i].y > test.y != this.points[j].y > test.y
                        && test.x < (this.points[j].x - this.points[i].x) * (test.y - this.points[i].y) / (this.points[j].y - this.points[i].y) + this.points[i].x) {
                    result = !result;
                }
            }

            return result;
        }
    }
}      

繼續閱讀