代码之家  ›  专栏  ›  技术社区  ›  Ozzy

php查找两点之间的坐标

  •  3
  • Ozzy  · 技术社区  · 15 年前

    简单的问题。假设我有两点:

    point 1
    
    x = 0
    y = 0
    
    
    point 2
    
    x = 10
    y = 10
    

    如果两点之间有一条海峡线,我如何以编程的方式找出它们之间的所有坐标呢?因此上面的示例将返回:

    0,0
    1,1
    2,2
    3,3
    ...
    8,8
    9,9
    10,10
    

    谢谢)

    5 回复  |  直到 13 年前
        1
  •  3
  •   Ozzy    15 年前

    谢谢你的帮助,但没有任何答案是我想要的。例如,假设我的观点是:

    0, 0

    0, 10

    只有开始和结束坐标…它找不到中间的。

    也许我做错了:S,但我想出了自己的解决方案:

    // Points
    $p1 = array(
        'x' => 50,
        'y' => 50
    );
    
    $p2 = array(
        'x' => 234,
        'y' => 177
    );
    
    // Work out distances
    $pxd = $p2['x'] - $p1['x'];
    $pyd = $p2['y'] - $p1['y'];
    
    // Find out steps
    $steps = max($p1['x'], $p1['y'], $p2['x'], $p2['y']);
    
    $coords = array();
    
    for ($i = 0; $i < $steps; ++ $i) {
        $coords[] = array(
            'x' => round($p1['x'] += $pxd / $steps),
            'y' => round($p1['y'] += $pyd / $steps)
        );
    }
    
    print_r($coords);
    
        2
  •  2
  •   jasonbar    15 年前

    您需要先找到线条的坡度:

    m = (y1 - y2) / (x1 - x2)
    

    然后你需要找到这条线的方程:

    y = mx + b
    

    在您的示例中,我们得到:

    y = 1x + b
    0 = 1(0) + b
    

    y = x
    

    要获得所有坐标,只需插入所有值x1->x2。在PHP中,整个过程看起来像:

    // These are in the form array(x_cord, y_cord)
    $pt1 = array(0, 0);
    $pt2 = array(10, 10);
    $m = ($pt1[1] - $pt2[1]) / ($pt1[0] - $pt2[0]);
    $b = $pt1[1] - $m * $pt1[0];
    
    for ($i = $pt1[0]; $i <= $pt2[0]; $i++)
        $points[] = array($i, $m * $i + $b);
    

    当然,这将为所有落在x整数值上的点提供坐标,而不是两个点之间的“所有坐标”。

        3
  •  1
  •   Alec Smart    15 年前
    1. 使用直线方程,y=mx+c
    2. 用(0,0)和(10,10)得到两个方程,求解得到m和c的值(你可以找到直接方程,得到m和c)。
    3. 然后创建一个循环,从x=x1(0)到x=x2(10)
    4. 使用y=mx+c,得到y的值(现在你知道m和c了)
        4
  •  1
  •   potlee    13 年前

    一个更简单的算法是,通过求出坐标的平均值来找到中点,重复这个过程直到完成为止。只是想指出,因为没有人这么做。

        5
  •  0
  •   Isaac    15 年前

    要在(x1,y1)和(x2,y2)之间的段上生成所有晶格点(具有积分坐标的点),其中x1,x2,y1和y2是整数:

    function gcd($a,$b) {
        // implement the Euclidean algorithm for finding the greatest common divisor of two integers, always returning a non-negative value
        $a = abs($a);
        $b = abs($b);
        if ($a == 0) {
            return $b;
        } else if ($b == 0) {
            return $a;
        } else {
            return gcd(min($a,$b),max($a,$b) % min($a,$b));
        }
    }
    
    function lattice_points($x1, $y1, $x2, $y2) {
        $delta_x = $x2 - $x1;
        $delta_y = $y2 - $y1;
        $steps = gcd($delta_x, $delta_y);
        $points = array();
        for ($i = 0; $i <= $steps; $i++) {
            $x = $x1 + $i * $delta_x / $steps;
            $y = $y1 + $i * $delta_y / $steps;
            $points[] = "({$x},{$y})";
        }
        return $points;
    }