How to generate a random convex polygon?

前端 未结 6 1171
南旧
南旧 2021-02-05 11:19

I\'m trying to devise a method for generating random 2D convex polygons. It has to have the following properties:

  • coordinates should be integers;
  • the poly
6条回答
  •  醉话见心
    2021-02-05 11:50

    Here is the fastest algorithm I know that generates each convex polygon with equal probability. The output has exactly N vertices, and the running time is O(N log N), so it can generate even large polygons very quickly.

    • Generate two lists, X and Y, of N random integers between 0 and C. Make sure there are no duplicates.
    • Sort X and Y and store their maximum and minimum elements.
    • Randomly divide the other (not max or min) elements into two groups: X1 and X2, and Y1 and Y2.
    • Re-insert the minimum and maximum elements at the start and end of these lists (minX at the start of X1 and X2, maxX at the end, etc.).
    • Find the consecutive differences (X1[i + 1] - X1[i]), reversing the order for the second group (X2[i] - X2[i + 1]). Store these in lists XVec and YVec.
    • Randomize (shuffle) YVec and treat each pair XVec[i] and YVec[i] as a 2D vector.
    • Sort these vectors by angle and then lay them end-to-end to form a polygon.
    • Move the polygon to the original min and max coordinates.

    An animation and Java implementation is available here: Generating Random Convex Polygons.

    This algorithm is based on a paper by Pavel Valtr: “Probability that n random points are in convex position.” Discrete & Computational Geometry 13.1 (1995): 637-643.

提交回复
热议问题