java - 获取线段上的所有点 - 已解决

标签 java

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

最佳答案

首先,确定该线是主要是水平的还是主要是垂直的。

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

如果它主要是水平的,则将xa.x迭代到b.x并计算y

如果它主要是垂直的,则将 ya.y 迭代到 b.y 并计算 x

我将让您构建正确的公式,或者在网络上查找它,即进行一些研究

关于java - 获取线段上的所有点 - 已解决,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61483124/

相关文章:

Java 设计问题

java - 通过 Android 提取 HTML 数据时出现问题

java - 如何为这样的表结构创建 DAO/模型

java - 如何找到数据库的最后一个条目

java - 进度条未显示在 webview 的 Relativelayout 中

java - 在 JSTL/EL 中如何获取集合中的第一个元素?

java - JNI(Java 和 C++)在 Ubuntu 11.10 上使用 Eclipse

Java - Thread - Sun 教程之一中的问题

java - 使用 Gson 将对象数组解析为字符串数组

Java 格式缩进 I/O