Click here to Skip to main content
15,890,897 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Can any one suggest algorithm or code for random polygon generation. Condition is that polygon sides are not intersect (means it should be like a convex polygon).
Posted
Updated 11-Sep-13 7:03am
v2

Now, one more, pretty obvious algorithm.

Create N points in same range, for example, the square on the points (0,0) and (1, 1), where N is a random number >= 3. For the obtained set of points, build a convex hull. You can find some algorithm if you read this: http://en.wikipedia.org/wiki/Convex_hull[^].

Apparently, you would need one intermediate step: a convex hull may appear to be a set of points on the same straight line, or too close to some line. The trick is to detect this situation (if your convex hull algorithm not fails) and through out this solution, repeat the attempt.

—SA
 
Share this answer
 
As the random distribution is not specified, I would suggest the following simple approach: start with a triangle, which is always a convex polygon except the case when all three point are on the same line, so throw out the cases when it happens. (As you are dealing with approximate floating-point arithmetic, never check anything for equality, create some '>' or '>=' criteria, in this case, for example, specify some minimal angle you would allow for a triangle). On next step, add a random point to replace a line segment (polygon side) with a two adjacent segments. On each step, it's easy to determine the constraints for a random point (new vertex) the way to keep the new polygon convex.

—SA
 
Share this answer
 
Comments
CPallini 11-Sep-13 2:00am    
Looks a good approach. My 5.
Sergey Alexandrovich Kryukov 11-Sep-13 2:44am    
Thank you, Carlo.
—SA
Sergey Alexandrovich Kryukov 11-Sep-13 13:01pm    
I just added another, simpler algorithm in Solution 3, please see...
—SA
Sergey Alexandrovich Kryukov 11-Sep-13 14:44pm    
And one more... :-)
—SA
I just got an idea of an alternative, simpler algorithm.

Start with a random triangle, as in Solution one, and, in a random number of steps, create a N+1-side polygon from an N-side using the "cut of a corner" operation. For this purpose, take two random but adjacent sides. In each side, choose a random point insider of the line segment representing a side. Connect these two points with a line segment, which should replace the "cut out" corner. This will create two new corners (vertices) instead of "cut-out" one. Proceed to the next step.

As it is easy to see, each step guarantees that a new polygon is convex provided the previous polygon was convex. As you start from a convex polygon (triangle), the polygon on each step is also convex.

—SA
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900