我找到了一个练习java类,我试图获取线段上的所有点,使得每个点x和y都是整数,但我在实现它时遇到了麻烦。我只是在寻找可以用来解决问题的公式。或者解释一下它是如何得到点(3,2)的。谢谢
/**
*
* @return an array containing all points on the line segment such that for every point in the array,
* both x and y are integers
* For example, if there is a line from (1,1) to (5,3), the only other point for which both x and y are
* integers is (3,2). Thus the method should return the array containing (1,1), (3,2) and (5,3)
* The order of points in the array returned should be from the point with lower x
* (use Point a as the starting point in case a.x == b.x).
*
* Hence if a = (5,1) and b=(1,3), the method returns an array such that
* first item is (1,3), second is (3,2) and third is (5,1)
*/
public Point[] getPointsOnCrosshair() {
Point[] points = new Point[20];
int counter = 0;
//getting slope of the line
double rise = this.b.y - this.a.y;
double run = this.b.x - this.a.x;
double m = rise/run;
System.out.println(m);
//getting value of c -> y = mx + c
double c = a.y - (m * a.x);
int start = 0;
int end = 0;
if (b.x >= a.x){
start = a.x;
end = b.x;
}
else{
start = b.x;
end = a.x;
}
// slope intercept y - y1 = m (x-x1)
// y = (m (x-x1)) + y1
double y = 0;
for (int a = start; a <= end; a++){
y = (m * a) + c;
if (y == (int) y){
points[counter] = new Point(a, (int) y);
counter++;
}
}
return points;
}
最佳答案
首先,确定该线是主要是水平的还是主要是垂直的。
▉ ▉ ▉
▉ ▉ ▉
▉ ▉ ▉
▉
▉
▉
如果它主要是水平的,则将x
从a.x
迭代到b.x
并计算y
。
如果它主要是垂直的,则将 y
从 a.y
迭代到 b.y
并计算 x
。
我将让您构建正确的公式,或者在网络上查找它,即进行一些研究。
关于java - 获取线段上的所有点 - 已解决,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61483124/