0

我正在寻找一种简短的智能方法来查找线段上的所有整数点。2个点也是整数,线的角度可以是0、45、90、135等度。

这是我的长代码(到目前为止是 90 度的情况):

def getPoints(p1,p2)
if p1[0] == p2[0]:
    if p1[1] < p2[1]:
        return [(p1[0],x) for x in range(p1[1],p2[1])]
    else:
        return [(p1[0],x) for x in range(p1[1],p2[1],-1)]
if p2[1] == p2[1]:
    if p1[0] < p2[0]:
        return [(x,p1[1]) for x in range(p1[0],p2[0])]
    else:
        return [(x,p1[1]) for x in range(p1[0],p2[0],-1)]

编辑:我说得不够清楚,但斜率总是整数-1、0或1,有8种情况需要检查。

4

5 回答 5

1

将斜率减小到最低项 (p/q),然后从线段的一个端点到另一个端点,垂直增量为 p,水平增量为 q。如果您的 reduce-to-lowest-terms 代码将 5/0 减少到 1/0,则相同的代码可以用于垂直线段。

于 2013-07-17T18:07:35.977 回答
0

i could write code that works, but the amount of repeating code is throwing me off, that's why i turned to you guys

This could stand a lot of improvement but maybe it gets you on the track. (sorry, don't have time to make it better just now!)

def points(p1,p2):
  slope = (p2[1]-p1[1])/float(p2[0]-p1[0])
  [(x,x*slope) for x in range (p1[0], p2[0]) if int(x*slope) == x*slope)]
于 2013-07-17T18:26:37.347 回答
0

对每对点做一些数学运算,计算 mx+c 的 m 和 c,并将其与您正在考虑的线的公式进行比较。(注意你得到一些除以零来应对。)

于 2013-07-17T18:12:58.187 回答
0

扩展@Jon Kiparsky 的答案。

def points_on_line(p1, p2):
    fx, fy = p1 
    sx, sy = p2 
    if fx == sx and fy == sy:
        return []
    elif fx == sx:
        return [(fx, y) for y in range(fy+1, sy)]
    elif fy == sy:
        return [(x, fy) for x in range(fx+1, sx)]
    elif fx > sx and fy > sy:
        p1, p2 = p2, p1  

    slope = (p2[1] - p1[1]) / float(p2[0] - p1[0])
    return [(x, int(x*slope)) for x in range(p1[0], p2[0]) if int(x*slope) == x*slope and (x, int(x*slope)) != p1]
于 2019-12-10T10:30:19.743 回答
-1
def getpoints(p1, p2):
  # Sort both points first.
  (x1, y1), (x2, y2) = sorted([p1, p2])
  a = b = 0.0

  # Not interesting case.
  if x1 == x2:
      yield p1

  # First point is in (0, y).
  if x1 == 0.0:
      b = y1
      a = (y2 - y1) / x2
  elif x2 == 0.0:
      # Second point is in (0, y).
      b = y2
      a = (y1 - y2) / x1
  else:
      # Both points are valid.
      b = (y2 - (y1 * x2) / x1) / (1 - (x2 / x1))
      a = (y1 - b) / x1

      for x in xrange(int(x1), int(x2) + 1):
          y = a * float(x) + b
          # Delta could be increased for lower precision.
          if abs(y - round(y)) == 0:
              yield (x, y)
于 2013-07-17T18:26:01.710 回答