一、核心代码理解

电子围栏核心代码理解与测试(待完善)_数据

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;
}
}
}