How to find a ray that intersects a polygon minimum times? - algorithm

Let P be a simple, but not necessarily convex, polygon and q an arbitrary
point not necessarily in P.
Design an efficient algorithm to find a line segment originating from q that intersects the minimum number of edges of P.

If q is your point in the space of 2D, we can write q(x,y). We know that a polyhedron have the edges(E), vertices(V) and faces(F) which all of this terms are related with the formula V - E + F = 2 from the Euler's theorem but the problem turns out to be easier since it is for a polygon.
So the plain is to find an edge and calcule the direction vector of the point q(x,y) to the center of the edge, doing this (and if the polygon is convex) we are sure that this line segment will only goes through one edge of P.
The calculation will need a little of linear algebra, but it is not that difficult, for example:
1 - Find the distance from a line to a point (so we can find the closest edge to use in this problem):
2 - Also, a good idea would be to find the point on this line which is closest to (x0,y0) has coordinates:
Where the equation of the line is ax + by + c = 0 and the (x0,y0) is an arbitrary point not necessarily in P.
So, now we can find the point k(x,y) on the line that is closest to the initial point q(x0,y0), doing |q-k| = d. Where d is the distance that we just calculate. After that you already have everything that you need to find a line segment originating from q that intersects the minimum number of edges of P.
Some places where you can study and find more about this topic:
Wiki
mathwords

Think of doing this on a map, so you can think of directions like North, South, East, West, and bearings.
If you have a ray going in a particular direction from q out to infinity, whether it intersects a line between points A and B depends only on the bearing of the ray, and the bearings from q to A and B: if the bearing of the ray is within the range spanned by the bearing from q to A and the bearing from q to B, taking this in the direction of the line, then the ray will intersect the line.
So you can reduce this to a simpler problem. Imagine that all the points are in a circle around q, and the lines are arcs of this circle. Now you need to find a point on this circle which is overlapped by the minimum number of arcs. You will also make life very much easier if you divide each arc that spans 0 degrees into two at 0, cutting e.g. an arc from 320 degrees round to 40 degrees into one from 320 degrees to 360=0 degrees, and one from 0 degrees to 40 degrees.
Good candidate points for this are points just clockwise of each point in the circle. Now order each arc so that it is from a low angle to a high angle, sort the arcs by low angle, and work through them in order, incrementing a counter when you see the start of an arc, and decrementing it when you see the end of an arc (you don't need to worry about arcs that wrap across 0=360 degrees because you have just made sure that there aren't any). The point you want to find is the one associated with the smallest value of the counter.

Taking q as the origin of the coordinates, compute the polar arguments of the vertices. This is done in linear time.
Then every edge spans an interval of angles. To handle the wraparound, you can split the intervals that cross the 360° border.
You turned the problem in an instance of 1D intervals overlap. This is readily solved in O(N Log(N)) time.

Related

Best dynamic data structure for 2d circle nearest neighbor

The title is most of the problem. I have a set of circles, each given by a center C and radius r. The distance between two circles is the Euclidean distance between their centers minus both their radii. For circles a and b,
d_ab = |C_a - C_b| - r_a - r_b.
Note this can be negative if the circles overlap.
Then what is the quickest data structure for finding the nearest (minimum distance) neighbor of a given circle in the set?
Adding and deleting circles with "find nearest" queries interleaved in arbitrary order must be supported. Nothing is known about the set's geometric distribution in advance.
This will be the heart of a system where a typical number of circles is 50,000 and 10's of thousands of queries, inserts, and deletes will be needed, ideally at user-interaction speed (a second or less) on a high end tablet device.
The point nearest neighbor has been studied to death, but this version with circles seems somewhat harder.
I have looked at kd-trees, quad trees, r-trees, and some variations of these. Both advice on which of these might be the best to try and also new suggestions would be a terrific help.
Cover trees are another possibility for a proximity structure. They don't support deletes (?), but you can soft delete and rebuild in the background to keep the garbage from piling up, which may be a useful technique for the other structures.
There's a reduction from the 2D circle problem to the 3D point problem with a funky metric that goes like this. (The proximity structures that you named should be adaptable.) Map a circle centered at (x, y) with radius r to the point (x, y, r). Define the length of a vector (dx, dy, dz) to be sqrt(dx**2 + dy**2) + abs(dz). This induces a metric. To find the circle nearest to a center (x, y) (the radius of the query circle is not relevant), do a proximity search at (x, y, R), where R is greater than or equal to the maximum radius of a circle (it may be possible to modify your proximity structure so that it's not necessary to track R).
From my experience implementing kd-trees and Voronoi diagrams on points, it will be significantly easier to implement kd-trees from scratch. Even if you reuse someone else's robust geometric primitives (and please do, to save your sanity if you go this route), the degenerate edge cases of Voronoi/point location take time to get right.
I propose the following heuristic using a KD-Tree or something else that allows for O(log N) nearest neighbor. Instead of using a single point and a radius to represented a circle. Use k equidistant points on a circle itself, plus the center of the circle, otherwise you might have issues with a small circle inside of a large circle. It's the same the same idea as using a regular polygon of k vertices to represent a circle. It is then possible to take one vertex and find it's nearest neighbor (ignoring the vertices on the same circle) to find an approximation as to what is the closest circle based on the closest regular polygon.
The performances are as followed:
Create the KD-Tree: O(kN log kN)
Remove/add Circle to KD-Tree: O(k log kN)
-Add or remove all k points of a circle within the KD-Tree
Nearest Circle query (Circle): O(k log kN)
-This is done by first removing all k points of the circle (O(k log kN)) as it's not terribly useful to find out that the nearest neighbor of a circle is unsurprisingly, the circle itself. Then for each k points in the circle, find the nearest neighbor (O(k log kN)). Once the nearest neighbors are found, the actual nearest (to within some error) is the the one with the smallest distance (after calculating the true distance based on point and radius) (O(1)).
I'd suggest either using k = log(N) if you prefer it to be fast or k = sqrt(N) if you prefer it to be accurate.
Also, it's possible I haven't considered some special case that causes issues, so watch out for them.
If there is a guarantee that circles don't have large radius, at least that maximum radius (R) is significantly smaller than area where circles are positioned, than I think it can be covered with standard space partitioning and nearest neighbour search.
When searching for circle in a set that has minimal distance to given circle, than radius of given circle doesn't matter (distance definition.) Because of that it is same if only center (point) is compared to set of circles.
With that it is enough to store set of circles in space partition structure only by there centers (set of points.) Circle adding and deleting is done in standard way for points. Finding of nearest circle to given point can be done in two step:
find nearest center to given point P. Say circle C with center c and radius r.
center of circle that is closer to P, by your distance, can be only in ring around P with inner radius r and outer radius R-d(P,c). It is enough to search partitions that intersect that ring for candidates.
It is possible to optimize search by combining these two steps. In first step, some of partitions of interest are already visited. By storing which partitions are visited, and circle with minimal distance found in these partitions, search in second step can be reduced.
Thanks to #David Eisenstadt for the idea of a 3d search structure. This is part of the best answer, though his strange metric is not needed.
The key is to look in detail at how nearest neighbor search works. I'll show this for quadrees. Kd-trees with k=3 are similar. Here is pseudocode:
# Let nearest_info be a record containing the current nearest neighbor (or nil
# if none yet) and the distance from point to that nearest neighbor.
def find_nearest_neighbor(node, target, nearest_info)
if node is leaf
update nearest_info using target and the points found in this leaf
else
for each subdivision S of node
if S contains any point P where dist(P,T) < nearest_info.distance,
find_neareast(S, target, nearest_info)
end
end
end
end
When this is done, nearest_info contains the nearest neighbor and its distance.
The key is if S contains any point P where dist(P,T) < nearest_info.distance. In a 3d space, of (x,y,r) triples that describe circles, we have
def dist(P,T)
return sqrt( (P.x - T.x)^2 + (P.y - T.y)^2 ) - P.r - T.r
end
Here P is an arbitrary point in an octant of an octree cuboid. How to consider all points in the cuboid? Note all components of T are effectively fixed for a given search, so it's clearer if we write the target as a constant point (a, b, c):
def dist(P)
return sqrt( (P.x - a)^2 + (P.y - b)^2 ) - P.r
end
Where we have left out c = T.r completely because it can be subtracted out of the minimum distance after the algorithm is complete. In other words, the radius of the target does not affect the result.
With this it is pretty easy to see that the P we need to obtain minimum dist to the cuboid is Euclidean closest to the target with respect to x and y and with the max represented radius. This is very easy and quick to compute: a 2d point-rectangle distance and a 1d max operation.
In hindsight all this is obvious, but it took a while to see it from the right point of view. Thanks for the ideas.

Algorithm for bisecting a set of points using a circle of fixed radius

Suppose I have a set of points in the Cartesian plane, defined by an array/vector of (X,Y) coordinates. This set of points will be "contiguous" in the coordinate plane, if any set of discontinuous points can be contiguous. That is, these points originated as a rectangular grid in which regions of points were eliminated by a prior algorithm. The shape outlined by the points is arbitrary, but it will tend to have arcs for edges.
Suppose further that I can create circles of fixed radius r.
I would like an algorithm that will find me the center X,Y for a circle that will enclose as close to exactly half of the given points as possible.
OK, try this (sorry if I have very bad wording: I didn't learn my Maths in english)
Step 1: Find axis
For all pairs of points, that are less than 2r apart calculate how many points lie on either side of the connecting line
Chose the pair with the worst balance
Calculate the line, that bisects these two points as an axis ("Axis of biggest concavity")
Step 2: Find center
Start on the axis far (>2r) away on the side, that had the lower point count in step 1 (The concave side)
Move the center on the axis, until you reach the desired point. This can be done by moving up with a step of sqrt(delta), where delta is the smallest distance between 2 points in the set, if overreaching move back halfing the step, etc.
You might want to look into the algorithm for smallest enclosing circle of a point set.
A somewhat greedy algorithm would be to simply remove points 1 at a time until the circle radius is less or equal to r.

Given a circle with N defined points and a point M outside the circle, find the point that is closest to M among the set of N. O(LogN)

http://www.glassdoor.com/Interview/Google-Interview-RVW2382108.htm
I have tried to come with a solution to this problem. But I have not been successful.. Can any one please give me a hint as to how to proceed with this problem.
I will take 2 pair of two points each. That is, I will make 2 chords. Find out their perpendicular bisector. Using those bisectors, I will find out the center of the circle...
Moreover, I will come up with the equation of the circle. And find the point of intersection of the point M with the circle... That should be closest point. However, that point may or may not exist in the set of N points
Thanks.
Assuming that the points on the circumference of the circle are "in-order" (i.e. sorted by angle about the circle's center) you could use an angle-based binary search, which should achieve the O(log(n)) bounds.
Calculate the angle A from the point M to the center of the circle - O(1).
Use binary search to find the point I on the circumference with largest angle less than A - O(log(n)).
Since circles are convex the closest point to M is either I or I+1. Calculate distance to both and take the minimum - O(1).
To find a point closest to M, we need to do binary elimination of points based on planar cuts. A little pre-processing of the input points is needed after which we can find a point closest to any given point M in O(lgn) time.
Calculate (if not given) polar representation of points in (r,θ) format where r is the distance from center and θ is the angle from x-axis in the range (-180,180].
Sort all N points in increasing order of their angle from x-axis.
Note that simple binary search of a point closest to M will not work here, e.g.,
if the given points are sorted such that θ = (-130,-100,-90,-23,-15,0,2,14,170), then for a point M with θ = -170, binary search will give -130 (40 degrees away) as the closest point whereas 170 (20 degrees away) is the closest point to M.
if we ignore the sign while sorting (thinking that it will produce correct output), our new sorted array will look like θ = (0,2,14,15,23,90,100,130,170), binary search for a point M with θ = -6 will yield the result should be either 2 or 14 whereas 0 is the closest point to M in this case.
To perform the search operation using planar cuts,
Find planar cut line passing through the center of circle and perpendicular to the line connecting the center of the circle with point M.
Eliminate half of the circular plane [90+θ,-90+θ) or [-90+θ,90+θ) depending upon on in which half of the plane M lies.
Make planar cuts parallel to the first cut and passing through the point in the middle of the previous plane and eliminate all points in the half of the plane farther from M until there are no points left in the nearer half of the plane, in which case eliminate the nearer half of the plane.
Keep on cutting planes till we are left with one point. That point is the closest point to M. The total operation takes O(lgn) steps.
In case the data is skewed and not uniformly spread in the circle, we can optimize our planar cuts such that each cut passes through the median (based on angle) of those points which are left in the search operation.

Find a set of points of a circle draped on a 3D height map

I have a height map of NxN values.
I would like to find, given a point A (the red dot), whose x and y coordinates are given (and z is known from the data, so A is a vertex of the surface) a set of points that lie on the circumference of the circle with center in A and radius R that are a good approximation of a circular "cloth" (in grey) draped on the imaginary surface described by the data points.
The sampling, the reciprocal distances between the set of points that I am trying to find, doesn't need to be uniform, but still I would like to find at least all the points that are an intersection of the edges of the mesh with the circle at distance R from A.
How to find this set of points?
Is this a known problem?
(source: keplero.com)
-- edit
The assumption that Jan is using is right: the samples form a regular rectangular or square grid (in the X-Y plane) aligned with [0,0]. But I would like to take the displacement in the Z direction into account to compute the distance. you can see the height map as a terrain, and the algorithm I am looking for as the instructions to give to an explorer that, traveling just on paths of given latitude or longitude, mark the points that are at distance R from A. Walking distance, that is taking into account all the Z displacements done so far. The explorer climbs and go down in the valleys too.
The trivial algorithm for this would be something like this. We know that given R, the maximum displacement on the x and y axis corresponds to a completely flat surface. If there is no slope, the x,y points will all be in the bounding square Ax-R < x < Ax+r and Ay-R
At this point, it would start traveling to the close cells, since if the perimeter enters the edge of one cell of the grid, it also have to exit that cell.
I reckon this is going to be quite difficult to solve in an exact fashion, so I would suggest trying the straightforward approach of simulating the paths that your explorers would take on the surface.
Given your starting point A and a travel distance d, calculate a circle of points P on the XY plane that are d from A.
For each of the points p in P, intersect the line segment A-p with your grid so that you end up with a sequence of points where the explorer crosses from one grid square to the next, in the order that this would happen if the explorer were travelling from A. These points should then be given a z-coordinate by interpolation from your grid data.
You can thus advance through this point sequence and keep track of the distance travelled so far. Eventually the target distance will be reached - adjust p to be at this point.
P now contains the perimeter that you're looking for. Adjust the sample fidelity (size of P) according to your needs.
Just to clarify - You have a triangulated surface in 3d and, for a given starting vertex Vi in the mesh you would like to find the set of vertices U that are reachable via paths along the surface (i.e. geodesics) with length Li <= R.
One approach would be to transform this to a graph-based problem:
Form the weighted, undirected graph G(V,E), where V is the set of vertices in the triangulated surface mesh and E is the set of edges in this mesh. The edge weight should be the Euclidean (3d) length of each edge. This graph is a discrete distance map - the distance "along the surface" between each adjacent vertex in the mesh.
Run a variant of Dijkstra's algorithm from the starting vertex Vi, only expanding paths with length Li that satisfy the constraint Li <= R. The set of vertices visited U, will be those that can be reached by the shortest (geodesic) path with Li <= R.
The accuracy of this approach should be related to the resolution of the surface mesh - as long as the surface curvature within each element is not too high the Euclidean edge length should be a good approximation to the actual geodesic distance, if not, the surface mesh should be refined in that area.
Hope this helps.

find a point non collinear with all other points in a plane

Given a list of N points in the plane in general position (no three are collinear), find a new point p that is not collinear with any pair of the N original points.
We obviously cannot search for every point in the plane, I started with finding the coincidence point of all the lines that can be formed with the given points, or making a circle with them something.. I dont have any clue how to check all the points.
Question found in http://introcs.cs.princeton.edu/java/42sort/
I found this question in a renowned algorithm book that means it is answerable, but I cannot think of an optimal solution, thats why I am posting it here so that if some one knows it he/she can answer it
The best I can come up with is an N^2 algorithm. Here goes:
Choose a tolerance e to control how close you're willing to come to a line formed from the points in the set.
Compute the convex hull of your set of points.
Choose a line L parallel to one of the sides of the convex hull, at a distance 3e outside the hull.
Choose a point P on L, so that P is outside the projection of the convex hull on L. The projection of the convex hull on L is an interval of L. P must be placed outside this interval.
Test each pair of points in the set. For a particular line M formed by the 2 test points intersects a disc of radius 2e around P, move P out further along L until M no longer intersects the disc. By the construction of L, there can be no line intersecting the disk parallel to L, so this can always be done.
If M crosses L beyond P, move P beyond that intersection, again far enough that M doesn't pass through the disc.
After all this is done, choose your point at distance e, on the perpendicular to L at P. It can be colinear with no line of the set.
I'll leave the details of how to choose the next position of P along L in step 5 to you,
There are some obvious trivial rejection tests you can do so that you do more expensive checks only with the test line M is "parallel enough" to L.
Finally, I should mention that it is probably possible to push P far enough out that numerical problems occur. In that case the best I can suggest is to try another line outside of the convex hull by a distance of at least 3e.
You can actually solved it using a simple O(nlogn) algorithm, which we will then improve to O(n). Name A the bottom most point (in case of tie choose the one that is has smaller x coordinate). You can now sort in clockwise order the rest of the points using the CCW. Now as you process each point from the sorted order you can see that between any two successive points having different angle with point A and the bottom axis (let these be U, V) there is no point having angle c, with U <= c <= V. So we can add any point in this section and it is guaranteed that it won’t be collinear with any other points from the set.
So, all you need is to find one pair of adjacent points and you are done. So, find the minimum and the second minimum angle with A (these should be different) in O(n) time and select any point in between them.

Resources