Advertisement
Guest User

Untitled

a guest
May 29th, 2015
226
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.76 KB | None | 0 0
  1. #!/usr/bin/python
  2. # -*- encoding: utf-8 -*-
  3. # pylint: disable=invalid-name,missing-docstring,bad-builtin,star-args
  4. from operator import itemgetter
  5. from math import atan2
  6. from functools import partial
  7.  
  8. def polar(x, origin):
  9. # atan2 range -> [-π, π]
  10. # return range -> [0, π] as our origin has the minimum y coordinate
  11. # CAUTION: based on the assumption that origin has the min-y-coordinate
  12. return atan2(x[1] - origin[1], x[0] - origin[0])
  13.  
  14. def ccw(a, b, c):
  15. """
  16. 1 | ax ay 1 |
  17. area(a, b, c) = - * | bx by 1 |
  18. 2 | cx cy 1 |
  19. a vector calculus application,
  20. counter-clockwise turn positive area.
  21. colckwise turn negative area.
  22. collinear zero area.
  23. """
  24. return ((b[0] - a[0])*(c[1] - a[1]) - (b[1] - a[1])*(c[0] - a[0])) > 0
  25.  
  26. def grahams(points):
  27. """
  28. :points:
  29. [(x1, y1), (x2, y2), (x3, y3), ..., (xn, yn)]
  30. """
  31. n = len(points)
  32. start = min(points, key=itemgetter(1))
  33. points = sorted(points, key=partial(polar, origin=start))
  34. hull = []
  35. for x in xrange(n):
  36. while len(hull) >= 2 and not ccw(hull[-2], hull[-1], points[x]):
  37. hull.pop()
  38. hull.append(points[x])
  39. return hull
  40.  
  41.  
  42. def main():
  43. from random import randrange
  44. points = [(randrange(20), randrange(10)) for _ in xrange(30)]
  45. hull = grahams(points)
  46. print 'original points'
  47. out = []
  48. for y in xrange(10, -1, -1):
  49. for x in xrange(20):
  50. out.append('*' if (x, y) in points else ' ')
  51. out.append('\n')
  52. print ''.join(out)
  53. print 'convex hull points'
  54. out = []
  55. for y in xrange(10, -1, -1):
  56. for x in xrange(20):
  57. out.append('*' if (x, y) in hull else ' ')
  58. out.append('\n')
  59. print ''.join(out)
  60.  
  61. main()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement