0

我找到了一个练习 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;
}
4

2 回答 2

0

蛮力解决方案非常简单:

int p1x = 1;
int p1y = 1;
int p2x = 5;
int p2y = 3;

int xdiff = p2x - p1x;
int ydiff = p2y - p1y;

for (int x = p1x + 1; x < p2x; ++x) {
    float y = ((float) x - p1x) / xdiff * ydiff + p1y;
    if (((int) y) == y) { // check if xx.0
        System.out.print(x);
        System.out.print(", ");
        System.out.println((int)y);
    }
}

但我确信有一种更优雅的方式,也许使用素数分解

于 2020-04-28T15:15:14.873 回答
0

首先,确定线条是大部分水平的还是大部分垂直的。

▉ ▉            ▉
    ▉ ▉        ▉
        ▉ ▉      ▉
                  ▉
                    ▉
                    ▉

如果它大部分是水平的,x则从a.xto迭代b.x并计算y

如果它大部分是垂直的,y则从a.yto迭代b.y并计算x

我会把它留给你来建立正确的公式,或者在网上找到它,即做一些研究

于 2020-04-28T14:58:41.367 回答