【问题标题】:Draw diagonals of an n-gon, effectively有效地绘制 n 边形的对角线
【发布时间】:2016-06-01 19:09:28
【问题描述】:

所以我在练习 python 时遇到了这个问题,但我想它适用于所有语言。我要在规则的 n 边形中绘制所有对角线,这很好,我设法做到了。但是,还有另一个标准,同一条线不得多次绘制。我对此的解释是乌龟(顺便说一句我使用乌龟图形)不能在相同的两个角之间移动两次,而不仅仅是你要抬起笔。我也一直在尝试找到解决方案一段时间,但我似乎无法弄清楚并且开始怀疑它是否可能。

这里有人知道是否可以为所有 n 边形做吗?如果是的话,你能给我一个提示吗?

对于那些不知道那是什么的人来说,这里有两个常规的 n 边形。 (我肯定没有)

Nonagon

Octagon

/问

编辑

感谢 John Kahn,我能够完成可解部分,正如他指出的那样,它只能在不均匀度数的规则 n 边形上完成。 这是我的解决方案的代码。你怎么看?

def nhorning(r, n, ):

    if n % 2 == 0:
        print("It can't be done")
        return None
    angl = (2 * pi) / n  # angle for calculating all the coordinates of the n-gon
    a = {}  # contains the destinations for each corners diagonals
    cord = {}  # contains the coordinates of each corner
    for x in range(n):
        cord[x] = [float("%.2f" % (r * cos(x * angl))), float("%.2f" % (r * sin(x * angl)))]  # all corners coordinates
    for i in range(n):  # the diagonals that are to be drawn from the corner "i"
        a[i] = [x for x in range(n)]
        a[i].remove(i)  # can't draw a diagonal to itself
    count = 0
    pu()
    goto(cord[0])  # you have to start on a corner
    pd()
    cordstring = str(cord)  # a list isn't hashable, so making the lists to a string

    while count < (((n-1) * n) / 2): # loops until all diagonals are drawn


        if str(list(pos())) in cordstring:  # should always be on the circles radius except in the beginning
            for i in range(len(cord)):
                if cord[i] == list(pos()):  # finds what corner the turtle is on
                    where = i

            diags = a[where]  # the diagonals not drawn from the corner

            dest = diags.pop()  # the corner to which a diagonal is to be drawn,
                                # removes it since the diagonal to that corner will be drawn

            nwhere = a[dest]    # the diagonals not drawn from the corner where a
                                #  diagonal is to be drawn next

            nwhere.remove(where)    # the diagonal from the destination corner to the current corner will be drawn next,
                                    # so can't be drawn again

            goto(cord[dest])  # draw the diagonal

            count += 1



    done()

【问题讨论】:

    标签: math optimization polygon


    【解决方案1】:

    TLDR

    您正在寻找Eulerian Path

    对于奇数个顶点可以做到这一点,但对于偶数个顶点是不可能的。

    说明

    "要知道为什么会这样,请注意每次路径经过一个顶点时,它使用连接到该顶点的两条边。因此,路径上除了第一个和最后一个顶点之外的所有顶点都需要度数偶数。在循环的情况下,第一个和最后一个顶点相同,因此所有顶点的度数都必须是偶数。 - For a square, but the concept applies to n-gons

    【讨论】:

      猜你喜欢
      • 2018-04-17
      • 2018-06-08
      • 2012-10-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-09-30
      • 2014-05-25
      • 1970-01-01
      相关资源
      最近更新 更多