0

我一直在尝试在 Python 中实现礼品包装算法,我目前有以下代码:

def createIslandPolygon(particleCoords):

    startPoint = min(particleCoords.iteritems(),key = lambda x: x[1][1])[1]

    check = 1

    islandPolygon = []

    particleList = []

    for key in particleCoords:

        particleList.append(particleCoords[key])

    currentPoint = startPoint

    while(currentPoint != startPoint or check == 1):

        islandPolygon.append(currentPoint)

        check = 0

        angleDict = {}
        angleList = []

        for point in particleList:

            if point != currentPoint:

                angleDict[(angleBetweenTwoPoints(currentPoint, point))] = point
                angleList.append(angleBetweenTwoPoints(currentPoint, point))

        smallestAngle = min(angleList)

        currentPoint = angleDict[smallestAngle]

    return islandPolygon

并用于计算极坐标:

def angleBetweenTwoPoints(p1, p2):

    p3 = (p1[0], p1[1] + 2)

    a = (p1[0] - p2[0], p1[1] - p2[1])
    b = (p1[0] - p3[0], p1[1] - p3[1])

    theta = ((a[0]*b[0]) + (a[1]*b[1]))
    theta = theta / (sqrt((a[0]*a[0]) + (a[1]*a[1])) * sqrt((b[0]*b[0]) + (b[1]*b[1])))
    theta = math.acos(theta)

    return theta

问题是代码似乎永远不会离开 while 循环,我不知道为什么。有谁有想法吗?

谢谢。

(是的,代码很粗制滥造,我只是快速将它们拼凑在一起)

编辑:打印出坐标似乎表明它们只在两个坐标之间跳跃。

4

1 回答 1

1

根据http://en.wikipedia.org/wiki/Gift_wrapping_algorithm你需要这样做:

   pointOnHull = leftmost point in S
   i = 0
   repeat
      P[i] = pointOnHull
      endpoint = S[0]         // initial endpoint for a candidate edge on the hull
      for j from 1 to |S|-1
         if (endpoint == pointOnHull) or (S[j] is on left of line from P[i] to endpoint)
            endpoint = S[j]   // found greater left turn, update endpoint
      i = i+1
      pointOnHull = endpoint
   until endpoint == P[0]      // wrapped around to first hull point

你有这个正确的:

   pointOnHull = leftmost point in S

还有这个:

  P[i] = pointOnHull

但这是我不确定的部分:

  (S[j] is on left of line from P[i] to endpoint)

相反,您会在它与所有其他点形成的所有角度中找到最小的角度。但根据维基百科,你想要的是它与所有其他点形成的所有角度中最左边的角度。我有一些处理角度的代码:

def normalizeangle(radians):
    return divmod(radians, math.pi*2)[1]



def arclength(radians1, radians2 = 0):
    radians1, radians2 = normalizeangle(radians1), normalizeangle(radians2)
    return min(normalizeangle(radians1 - radians2), normalizeangle(radians2 - radians1))



def arcdir(radians1, radians2 = 0):
    radians1, radians2 = normalizeangle(radians1), normalizeangle(radians2)
    return cmp(normalizeangle(radians1 - radians2), normalizeangle(radians2 - radians1))

arcdir将告诉您一个角度是在另一个角度的左侧还是右侧,因此您可以使用它来查看一个角度是否更左侧,因此应该使用。

如果您沿着点移动总是选择最左边的角度到下一个点,您将绕过多边形的周边并再次到达起点(因为您选择了最左边的点,您知道它必须在周边上并且会再次到达)

于 2013-03-12T23:08:57.033 回答