r/dailyprogrammer • u/Elite6809 1 1 • Aug 08 '14
[8/08/2014] Challenge #174 [Hard] Convex Hull Problem
(Hard): Convex Hull Problem
I have a collection of points, called P. For this challenge the points will all be on a 2D plane. The Convex Hull problem is to find a convex polygon made from points in P which contains all of the points in P. There are several approaches to this problem, including brute-force (not good) and several O(n2) solutions (naive, not brilliant) and some fairly in-depth algorithms.
Some such algorithms are described here (a Java applet, be warned - change the display to 2d first) or on Wikipedia. The choice is yours, but because you're in /r/DailyProgrammer try and challenge yourself! Try and implement one of the more interesting algorithms.
For example, a convex hull of P:
- Cannot be this because a point is excluded from the selection
- Also cannot be this because the shape is not convex - the triangles enclosed in green are missing
- Looks like this. The shape is convex and contains all of the points in the image - either inside it or as a boundary.
Input Description
First you will be given a number, N. This number is how many points are in our collection P.
You will then be given N further lines of input in the format:
X,YWhere X and Y are the co-ordinates of the point on the image. Assume the points are named in alphabetical order as A, B, C, D, ... in the order that they are input.
Output Description
You must give the convex hull of the shape in the format:
ACFGKLOWhere the points are described in no particular order. (as an extra challenge, make them go in order around the shape.)
Notes
In the past we've had some very pretty images and graphs from people's solutions. If you feel up to it, add an image output from your challenge which displays the convex hull of the collection of points.
8
u/XenophonOfAthens 2 1 Aug 08 '14 edited Aug 08 '14
I actually did this a little over a year ago using the Graham scan, so I thought "screw it, I'll just implement it from memory!". It was a good thing you asked us to draw those pretty pictures, because they showed right away that I had totally forgotten how the Graham scan worked, and I had to spend the next half hour looking at the pseudo-code from wikipedia to find out where I went wrong. Pride goeth before the fall, and all that :)
In the end, it turned out pretty well. On my crappy 2010 MacBook Pro, finding the convex hull for 1,000,000 points took 5 seconds, which is a bit slower than I'd like, but still pretty ok. Doing it in PyPy would undoubtedly speed it up a bunch, given that it's a CPU-bound algorithm.
Anyway, here's my code (in Python 2/3), the bulk of which is used to draw pretty pictures like this:
7
u/skeeto -9 8 Aug 09 '14 edited Aug 09 '14
C99, using Graham scan. I mention C99 specifically because it's using variable-length arrays (VLA). I'm using GNU's qsort_r() so that the comparison function can be re-entrant (doesn't require a global variable). Instead of using letters, which doesn't scale well, it prints out the hull's vertex indices, 0-indexed from the input.
Here's the convex hull of 65,536 vertices with normally-generated positions. It only takes about a hundred milliseconds to compute.
4
u/YuriKahn Aug 08 '14 edited Aug 08 '14
I did mine in Java using Andrew's algorithm, and Swing for visuals. It's not the prettiest thing, but it certainly works.
This wasn't too hard considering that pseudocode was freely available from the problem description, but oh well.
UPDATE! I've worked on the interface more! I made the colors a little less garish, added antialiasing, etc, so it looks nicer. However, the big addition is that you can select and drag points with the mouse and the program recalculates the borders automatically in real time. While this may appear slow or inefficient, it runs beautifully on my 8 year ond crap-top.
Old visuals
New visuals
The green dot is the one that I have currently selected.
I've discovered a few minor glitches (I think I'm not sorting it correctly for the algorithm)Fixed.
Source (Feedback welcome!): http://pastebin.com/xjBw2NpT
Test input: http://pastebin.com/7jxebfLf
4
u/Frichjaskla Aug 08 '14
C++/SDL2
Graham scan inspired by wikipedia
Input is via mouse and it animates the algorithm.
Smiley: http://i.imgur.com/g6L4MRl.gif
When I thought I was done and everything was great: http://i.imgur.com/O5aRHdf.gif
The bug was that i forgot to advance the iterator in the init routine
Code: https://gist.github.com/anonymous/de5f480f5e993f845f5c
4
u/MaximaxII Aug 08 '14 edited Aug 08 '14
I tried QuickHull at first because no one had done it yet, but learned that implementing PIP (the Point in Polygon problem) was a pain.
So I went with the Gift Wrapping Algorithm.
Output
For 50 points:
http://i.imgur.com/gsCdTPF.png
For 26 points:
http://i.imgur.com/YgMZY0q.png
Challenge #174 Hard - Python 3.4
3
u/zifu Aug 09 '14
Javascript!
Using Graham scan. I get an error (index out of bounds) with more than like 10000 points though, dunno what's wrong.
Live version
Output
2
u/ENoether Aug 08 '14
Python 3.4.1, using the Graham scan. I use a slightly different input format, where I take the points as a list of coordinates. It will have problems if the first three points it encounters are collinear. As always, feedback and criticism welcome:
Code:
Run:
Output:
2
u/nullmove 1 0 Aug 08 '14
Graham Scan in Haskell:
Can anyone conjure up a big and wicked dataset where points have equal or pretty close angle with respect to the pivot? Floating point imprecision was really messing up my sort order in such cases.
2
u/marchelzo Aug 09 '14 edited Aug 09 '14
Andrew's monotone chain in Haskell. I used Diagrams to produce the output. It seems really interesting but I haven't gotten the hang of it quite yet so the pictures aren't all that pretty.
http://imgur.com/70cafSh
1
u/lukz 2 0 Aug 08 '14 edited Aug 08 '14
vbscript
I chose a simple algorithm for the solution but also provided a simple ascii image of the output.
I use a different input format, the point coordinates are separated by a space.
Example input:
Gives this output:
Code:
1
u/dohaqatar7 1 1 Aug 08 '14 edited Aug 08 '14
I implemented QuickHull in Haskell.
It works fine but found that I had to make the functionfindHullas well asfindHull'. Both accomplish the same task, butfindHullfor the left half of the points andfindHull'for the right. The difference between them is minuscule, but being a novice at Haskell, I can't figure out how to avoid the the code duplication that arises from this issue. Help?Never mind guys, /u/wadehn was able to help me out.
Output
1
u/cjs19909 Aug 09 '14
Ruby
I tried doing this with a graham scan. I think it mostly works but it doesn't handle vertical lines quite right. It also needs to be re-factored pretty badly, but I'm feeling a little burnt out on it. Any suggestions would be appreciated.
Code:
Input:
Output:
1
u/mennovf Aug 09 '14
Haskell implementation, took me hours to find a bug. Turned out I was ignoring the first input line (the number of lines, as this isn't needed) and forgot to make my test data conform.
The hardest part was reading the input and transforming the result back. This solution returns every vertex on the hull, not only the extremes.
Any critiques are welcome as I'm sure this could be simplified.
Use as such:
runhaskell file.hs < data.txt
1
u/[deleted] Aug 09 '14
Java-8 using Graham scan
1
u/viciu88 Aug 09 '14 edited Aug 09 '14
Java
QuickHull algorithm implementation I did for school. Just added input and saving to image. 1,000,000 points takes about 3 seconds on my 2007 PC.
source: http://pastebin.com/JHC5bfzG
result: http://imgur.com/EcEa4Np
1
u/rsicher1 Aug 10 '14 edited Aug 10 '14
Ruby. Extended the Math module to add some useful geometry functions for this challenge (line distance, arccos triangle, degree conversion). Created a ScatterPlot class to handle building the scatter plot and house the convex hull related methods. Performs a Graham Scan to build the convex hull. Inputs for number of vertices and points are validated via regex to ensure specific formatting. In addition, points inputs are checked for uniqueness.
Edit: I was using geometry formulas like line distance and arccos triangle to calculate the angles of points relative to the convex hull start point (to ultimately order the points in CCW fashion). However, after reviewing other solutions, I realized this was unnecessary because the same thing could be accomplished more efficiently using atan2. I updated the logic accordingly. As a result of this change, I removed the Math module logic since there was no longer a need for the additional geometry functions.
Sample Input -
Sample Output -
1
u/BriskMorning Aug 11 '14
My first submission here. I used Javascript and HTML5 canvas. I've decided not to check any existing solutions to this problem and try to come up with my own algorithm instead (it's more fun that way ;)). My algorithm works like this: first it finds four points with the lowest/highest x/y coordinates: "left", "up", "right" and "down". Those points are always part of the convex hull. Then we need to find hull points between each pair of them, going clockwise starting from left-up, then up-right, right-down and down-left. Between each two of those extreme points we draw a line and then check if there are any points on the "left" side of the line (or, on the "outside") or on the line itself. We do this by calculating the distance from each point to the line between points we're currently checking. The distance is calculated using simple linear equations: we calculate the equation of the line going through two initial points and the equation of the line that goes through each point we're checking and that is perpendicular to the first one. If there are no points, function ends. If there are, we select the point that is farthest away from the line (and is part of the hull) and recursively apply the procedure to two pairs of points: first initial point and the farthest point, the farthest point and second initiial point. That way we find all the points that are part of the hull in the selected quarter. Then the algorithm does the same for the remaining three pairs of points with lowest and highest coordinates.
Whew, I bet this sounds very chaotic and confusing or is just plain incomprehensible, but there it is. Feedback would be welcome! You can either click on the canvas to add points or give the number of points and enter the coordinates manually (or randomize them).
Edit: output looks like this: http://i.imgur.com/x8cwuAb.jpg
1
u/markus1189 0 1 Aug 11 '14 edited Aug 12 '14
QuickHull in haskell using diagrams to draw a nice picture and QuickCheck to generate random points (if input not via stdin)