-1

I'm generating random coordinates in Python for each of the vertex as follows:

n = 10
V = []
V=range(n) #vertices

random.seed(1)
points = []

for i in V:
    x = random.randint(0,50)
    y = random.randint(0,50)
    points.append((x,y))

I need to create a closed polygon using these vertices. Can someone please provide me a suggestion for this?

ccc
  • 574
  • 2
  • 9
  • 22

2 Answers2

4

If you don't want intersections, one way to achieve this is to order your co-ordinate pairs after some rotation rule. In the example above, I first define a center point (here just the average of all x- and y-values, respectively) and then compute the angle that each co-ordinate pair defines with that center point. As JRG already said, you get a closed polygon by appending the first point to your sequence of points:

import numpy as np
from matplotlib import pyplot as plt

def draw_polygon(ax, n):

    x = np.random.randint(0,50,n)
    y = np.random.randint(0,50,n)

    ##computing the (or a) 'center point' of the polygon
    center_point = [np.sum(x)/n, np.sum(y)/n]

    angles = np.arctan2(x-center_point[0],y-center_point[1])

    ##sorting the points:
    sort_tups = sorted([(i,j,k) for i,j,k in zip(x,y,angles)], key = lambda t: t[2])

    ##making sure that there are no duplicates:
    if len(sort_tups) != len(set(sort_tups)):
        raise Exception('two equal coordinates -- exiting')

    x,y,angles = zip(*sort_tups)
    x = list(x)
    y = list(y)

    ##appending first coordinate values to lists:
    x.append(x[0])
    y.append(y[0])

    ax.plot(x,y, label = '{}'.format(n))

if __name__ == '__main__':

    fig,ax = plt.subplots()

    for n in range(3,11,2):
        draw_polygon(ax,n)

    ax.legend()
    plt.show()

The result looks something like this: several random polygons

Thomas Kühn
  • 9,412
  • 3
  • 47
  • 63
0

Given n, generate only n-1 random vertices and at the end add the first element in the list as the nth element to get the closed polygon.

NOTE: you would need to special handling that the newly generated vertex is not already present in the list

To find if the vertices form a real polygon, found below article

https://math.stackexchange.com/questions/52733/equation-to-check-if-a-set-of-vertices-form-a-real-polygon

import random

n = 10
V = []
V = range(n-1) #vertices

random.seed(1)
points = []

for i in V:
    x = random.randint(0,50)
    y = random.randint(0,50)
    points.append((x,y))

points.append(points[0])
print(points)

Sample Run

======== RESTART: C:/polygon.py ========
[(8, 36), (48, 4), (16, 7), (31, 48), (28, 30), (41, 24), (50, 13), (6, 31), (1, 24), (8, 36)]
JRG
  • 4,037
  • 3
  • 23
  • 34
  • This does not guarantee that there will be no self-intersections. – DYZ Aug 23 '17 at 05:24
  • Hi JRG, thanks for your answer. But, how can we connect these points with lines to make a closed polygon? – ccc Aug 23 '17 at 05:25