【问题标题】:divide ways on a map in parts of length one将地图上的路径分成长度为一的部分
【发布时间】:2011-02-12 10:50:02
【问题描述】:

我有这些坐标:

coord = [(10,10), (13,10), (13,13)]

现在我需要新的坐标。 两个坐标之间的路总是一。 例如:

(10,10)
(11,10)
(12,10)
(13,10)
(13,11)
(13,12)
(13,13)

有什么想法吗?

#

我找到了解决办法。

for n in range(len(coord)-1):
    lengthx = coord[n+1][0] - coord[n][0]
    lengthy = coord[n+1][1] - coord[n][1]
    length = (lengthx**2 + lengthy**2)**.5
    for m in range(length):
        print coord[n][0]+lengthx/length*m, coord[n][1]+lengthy/length*m

【问题讨论】:

  • 乍一看像Python,但提问者一定要加个语言标签。
  • @kame,xy 可以在同一个步骤中变化吗?例如。我们可以假设[(10, 10), (12, 12)] 给出[(10, 10), (11, 11), (12, 12)]吗?
  • 好的 - 这真的很愚蠢,但是 both 副本刚刚关闭!我们应该重新打开其中一个!
  • (投票重新开放,因为骗子也被关闭了,提问者在这里提供了更多信息。)
  • 抱歉重复发帖。意外!

标签: python arrays algorithm


【解决方案1】:

Bresenham's line algorithm 的简单变体将仅使用整数算术实现您想要的(因此它应该明显更快):

def steps(path):
    if len(path) > 0:
        for i in range(1, len(path)):
            for step in steps_between(path[i - 1], path[i]):
                yield step
        yield path[-1]


def steps_between(start, end):
    x0, y0 = start
    x1, y1 = end

    steep = abs(y1 - y0) > abs(x1 - x0)
    if steep:
        x0, y0 = y0, x0
        x1, y1 = y1, x1

    if y0 > y1:
        x0, x1 = x1, x0
        y0, y1 = y1, y0

    if y0 < y1:
        ystep = 1
    else:
        ystep = -1

    deltax = x1 - x0
    deltay = abs(y1 - y0)
    error = -deltax / 2

    y = y0
    for x in range(x0, x1):
        if steep:
            yield (y, x)
        else:
            yield (x, y)

        error += deltay
        if error > 0:
            y += ystep
            error -= deltax
            if steep:
                yield (y, x)
            else:
                yield (x, y)

coords = [(10, 10), (13, 10), (13, 13)]
print "\n".join(str(step) for step in steps(coords))

以上打印:

(10, 10)
(11, 10)
(12, 10)
(13, 10)
(13, 11)
(13, 12)
(13, 13)

当然,当xy 在路径上的两点之间变化时,Bresenham 会按预期工作:

coords = [(10, 10), (13, 12), (15, 13)]
print "\n".join(str(step) for step in steps(coords))

打印出来的:

(10, 10)
(11, 10)
(11, 11)
(12, 11)
(12, 12)
(13, 12)
(14, 12)
(14, 13)
(15, 13)

【讨论】:

    猜你喜欢
    • 2013-09-26
    • 1970-01-01
    • 2020-11-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-02-05
    相关资源
    最近更新 更多