r/programmingchallenges • u/thechipsandgravy • Oct 07 '11
Challenge: Reflective Symmetry
Given a simple polygon (closed, non self-intersecting), write a program to determine if it is reflectively symmetric. Bonus points if the run time complexity of your algorithm is O(N2 lgN) or better.
3
u/okmkz Oct 08 '11
An odd number of vertices will be quicker to process, undoubtedly. This one is fairly complex, but also pretty intuitive.
2
u/VeeFu Oct 11 '11 edited Oct 11 '11
I think it should be about the same amount of work. For the odd case, you'd have to test N potential lines of symmetry, which would be between each vertex and the midpoint of the opposite pair of vertexes.~~For the even case, you have to generate potential lines of symmetry for each vertex to its opposite vertex, and for each midpoint to it's opposite midpoint. However, if you've gotten half-way 'round the polygon and haven't succeeded in finding a line of symmetry, you can give up. ~~
Edit: no, you were right... if my O calculation is correct, my algorthm performs in O( ( N2 - N ) / 2 ) in the odd case and O( N2 - N ) in the even.
1
u/TimeWizid Dec 29 '11
Interesting challenge! I made a variation of VeeFu's solution:
Find the potential lines of symmetry.
For each potential line of symmetry, move and rotate the polygon so that the line is vertical and on the Y axis. That way a symmetric pair of vertices will have the same Y values and opposite X values.
The nice thing about this algorithm is there's already a library for rotating vertices, and comparing them after they've been rotated is much simpler. I believe this is O( N2 ).
2
u/VeeFu Oct 11 '11
Well... I'm not particularly pleased with the code... but here it is, in C++. If you have more insidious tests to run I'd be happy to add them.
The traversal was tricky. I think it would have been easier and more clear if I had used a deque instead of vector and modified the deque between outer iterations. Something like push_back(pop_front()).