Python中的礼品包装算法永远不会终止

时间:2013-03-12 22:57:17

标签: python algorithm geometry

我一直在尝试用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循环,我不知道为什么。有没有人有任何想法?

感谢。

(是的,代码非常粗制滥造,我只是把它快速扔到一起)

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

1 个答案:

答案 0 :(得分: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会告诉您角度是在另一个角度的左侧还是右侧,因此您可以使用它来查看角度是否更左,因此应该使用。

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