Does this algorithm work? [closed] - algorithm

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 5 years ago.
Improve this question
The given problem is to find a way to efficiently return all boxes hit by a ray.
So I came up with an idea but I want to know your opinion before I waste time in programming something not working.
Basically, the idea is to have a grid of boxes with height = width, all of these boxes are the same size and they don't have a gap between each other, I also have a function to calculate the box index which belongs to a point.(in which box the point is)
Now I calculate a box around the grid and calculate the hit points of a ray with the edges.
So I know the intersection points and of course the direction of the rays, now I take the direction, normalize it and divide it by 2. ( I'm not really sure if I need /2 but I feel better with it)
The resulting vector is now my "step size". (I call this vector v)
So if I take now my first intersection point add v, calculate the box which belongs to the resulting point and does this again and again until I reach my second intersection point I shouldn't miss any box. (right?)
But I'm not sure about that so I ask for your opinion.

This algorithm does not work completely, because in any given square you can take a path through it (by cutting corners) that was a lower distance than whatever you put your step size as. This means that, no matter what you make your step size is, certain vectors will cause this function to omit blocks. That being said, if you use a smaller step size (say v=.05), this isn't a bad estimation algorithm (supposing the grid isn't too large).
Edit: Here is an algorithm that will work. Do the step size thing you are doing with step size < 1 (I think v = .9 should be fine), but after each step, check the relation of each box to the previous one. If you are in the same box or an adjacent box, do nothing. If you are in a diagonal box, you probably passed through an adjacent box to get there. Figure out if and which one it was, and also add it to your list.

Related

What is the shortest path that touches every tile in a square grid? [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 8 years ago.
Improve this question
Suppose a ant is placed on the position (0,0) of a chess-board. That ant wants to walk through every single tile of the board, while walking the least it can to do so. What path it must follow? Is there a formula F(i) that returns the position of the ith tile on that path?
Edit: as requested, I've tried the following:
I tried googling for keywords such as "shortest path", "shortest path in square grid", but couldn't find anything relevant.
I then downloaded, configured and used a Traveling Salesman Problem solver in a square grid. Obviously, the solution wasn't satisfactory, but I could gain an insight on the problem. There is an illustration of my results:
I then, intuitively, speculated wether the answer could be something like the Hilbert Curve: . I googled about it and asked on a IRC programming channel, but I couldn't find any actual evidence this is better than spirals and similars, nor a proof this is the best possible solution.
EDIT 2: Further clarifications:
The ant can move diagonally. The distance refers to the euclidean length of the line defined by the path.
Walk in straight line, with the edge of the board on your left, until you either hit the edge of the chess board or a tile you have visited before. If you do, then take a right.
Or a thousand other obvious patterns.
Any path that takes 63 steps is the minimum and just as good as any other path.
This is going to depend on if you're taking the width of each square into consideration or is this just a double array question?
If we're talking a double-array question f(x,y), then the answer is that there is no least path because the ant will need to travel to each square f(x,y) = x*y, so f(8,8) = 64.
If we start taking the width of the tiles themselves into consideration, then the answer is somewhat different because we can use some strategies to get the least amount of distance traveled (such as starting in the center, staying by the grid separators and walking in a roughly spiral pattern r=xy^(theta)).

how to fit polygon inside another polygon [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
I have two polygons as shown in the image below.
The left one is "rough polygon" and the right one is "final polygon"
Now, I'm looking for algorithm to fit "final polygon" inside "rough polygon" with best maximum scale.
you can rotate as well as translate "final polygon" as much as you want.
you can't perform individual x dimension or y dimension scaling.
you can only perform uniform scaling (where value of Sx and Sy are same).
Here is a possible line of attack for an exact solution by exhaustive trials; just ideas.
My guess is that a solution is achieved when there are three contacts. I mean three vertexes of either polygon touching an edge of the other or conversely. (If there are less than three contacts, you can inflate the internal polygon so that it comes into a third contact.)
Given two arbitrary triangles, it shouldn't be so difficult to find all possible three-contact positions.
So the global scheme is to take all triples of vertexes/sides from one polygon, and take all complementary triples of sides/vertexes of the other. For every combination, momentarily consider that you have triangles and find the possible three-contact positions. For for every candidate position check if the inner polygon stays confined in the outer one. In the end, keep the admissible solution with the largest scale factor.
For polygons with N and M sides, there will be O(N³M³) configurations to try, and the containment test can be as costly as O(NM). So this approach is only viable for very small polygons.
Scale the rightside polygon by 0.01. (geometrical)
Start spinnning it so fast that it draws circle. (geometrical)
Start incrementing the scale 0.01 by 0.01. (geometrical)
Stop when it touches the outer polygon. (geometrical)
Then bounce it to opposite direction until it bounces again. (physical)
Again and again.(iterations)
Until it cannot move/bounce again.(stuck optimally) (physical)
Use simulated annealing in case of false local solutions.(you need global solution)

How can I divide a rectangular area into smaller rectangles that represent a percentage of the total area? [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
Basically I'm trying to get a "nice" image where all the small rectangles add up to the big rectangle, kind like:
*Later Edit to clarify some things:
I want to be able to draw something like this in a piece of software. So, what I need is closer to an algorithm.
All I need are some rectangles. I don't need them to have some predefined proportions just that they look like a rectangle. Anything between a square and a 3:1 width/height (or height/width) is fine. The extremely naive approach would be to just divide the width of the enclosing rectangle into the percentage that enclosed rectangles have but this will create thin slices and some of the smaller percentage rectangles will drop bellow 1px.
I need to find a way to split the rectangles on multiple rows.
*Second Edit: Problem SOLVED. I was looking for a TreeMap algorithm (as pointed out by Phpdna). Once I had the keyword I was able to quickly find a couple of python implementations that satisfied my requirements.
Treemap is an algorithm that can pack smaller rectangles into a map. You can recursively subdivide a plane into smaller tiles for example by splitting the plane along the 2 axis and save the result to a tree.
This approach guarantees that the small rectangles always cover the initial rectangle. so does any other approach which starts by constructing rectangles within an existing set of rectangles.
Draw a straight line from one edge of the plane to the opposite edge and parallel to the other two edges. Draw it in a location which produces 2 rectangles whose proportions are pleasing to your eye.
If you want another rectangle, draw a line from the first line, perpendicular to it, and extend that line to the edge of the plane. Again, choose its position so that the line creates rectangles of pleasing proportions. Now you have 3 rectangles.
Now, to get the 4th rectangle, choose one of the existing lines to start from and draw a line perpendicular to it until it reaches either the edge of the plane or an existing line. Again, take care to ensure that the proportions of the rectangles created are pleasing to your eye.
Continue until you have all the rectangles you want.
Personally I think that the above is the easy part, the difficult part is determining algorithmically where to draw the lines. I suggest you think of the Golden Ratio, it cousins the Fibonnaci numbers and other ratios such as the basis of the A series of paper sizes, ie 1:sort(2).

Checking convexity from outside [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
Is there any method or algorithm to determine convex (or non-convexity) property of a region from outside (perimeter) ?
One way is plotting tangent line in each point of perimeter and discuss how many times this line intersect the perimeter points. If no intersect shown (for all points of perimeter ) we can conclude region is convex. In otherwise region is non-convex.
Second way is determine interior angel of each point of perimeter and discuss if it's bigger than 180 or not. The region is non-convex if at least one point in perimeter exist it's interior angel bigger than 180.
Are there another simpler ways?
Any ideas or solution would be appreciated, thanks.
One thing to observe when doing this is that as you traverse the sides of a convex polygon, all the turns will be to the same side. That is, if you are traversing around the vertices in a counter-clockwise direction, all of the turns will be to the left; if you are traversing around the vertices in a clockwise direction, all of the turns will be to the right. If you ever observe a turn to the opposite side of any others observed, then you know you're dealing with a non-convex polygon. If all of the turns are to one side, then it is a convex polygon.
So, all you need to do is take look three vertices at a time, call them vn, vn+1 and vn+2. You can then determine which side of the line segment connecting vn and vn+2 the vertex vn+1 sits on. For CCW, vn+1 should be on the right of the line segment, and for CW it should be on the left. There is an answer to another question which provides a method for determining this.
There are additional implementation details you should work out (like how to deal with n=N, the number of points in your polygon, but this should provide you with a place to start.
An implementation based on this approach will run in O(N) time and space.
UPDATE: In response to the question below, "how about non-polygonal regions"? In general this is much harder. Mathematically, a region can be shown to be non-convex by finding a line segment with endpoints in the interior of the region but which has some portion of the line segment exterior to the region. I suspect you're looking for a way of implementing this using a digital computer, and so the pure mathematical approach is not practical.
So, you're going to have to offer some sort of constraints as to the types regions before the problem becomes intractable. That is, you have to constrain your problem space so that things like Nyquist sampling of the perimeter of the boundary do not incorrectly identify a non-convex region as being convex.
Assuming you can properly constrain the problem, any solution you can come up with, which can be implemented on a digital computer will have to approximate the region. You can either generate a piece-wise linear approximation of the region in question and run the algorithm above, or pick the proper set of points along the boundary of the region and calculate their derivative. Each successive sample should rotate the angle of the tangent line by some increment in the same direction. But again, it gets downs to sampling.
If you have other information about the nature of any nonlinearities which comprise the boundary of your region, you may be able to symbolically demonstrate whether a segment of the boundary is convex. The problem then reduces to showing that it remains convex when joined to the adjacent sections, which again is going to be problem specific.
So, my suggestion is, for digital computer implementation, approximate as needed the boundary of the region by a polygon and run the method defined above on that approximation.
An algorithm I've used (in pseudo code):
function isConvex(vertices[Count] V):
convex = true
if Count <= 3 return convex
for N = 0 to Count while convex:
// line segment between previous and subsequent vertices
LineSegment segment1 = new LineSegment(
V[(N + Count - 1) % Count], V[(N + 1) % Count]);
// line segment between the point and any other point
LineSegment segment2 = new LineSegment((V[N], V[N+2 % Count]);
if not segment1.intersects(segment2) then convex = false;
return convex
I don't know if this is optimal or simpler than the algorithms you've already tried.
The LineSegment.intersects() method already existed making this really easy to write.
The actual code used segment2 from the previous iteration as segment 1 of the current iteration making it faster but more complex to write even in pseudo code.
And also, for what it's worth, the original of this algorithm was written in assembly language on a processor that no longer exists, so I won't be providing actual code ;-).

Finding centre of rotation for a set of points [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
If I have an arbitrary set of points, and then the same set of points rotated by some degree, does anyone know of any algorithms to calculate/estimate where the centre of the rotation is? Or an area of study where these kinds of algorithms are needed?
I am having trouble finding any relevant information.
Thanks
Lets say you have one point (x, y), that moved to (x', y').
Then the center of rotation must lie on the line that is perpendicular to (x,y)-(x',y'), and that intersects the center (x,y)-(x',y').
Now take another point, (x2, y2), that moved to (x'2, y'2). This also gives rise to a line on which the center of rotation must be located on.
Now take these two lines and compute the intersection. There you have the center of rotation.
Update: If you don't have the correspondence of which point went where, it shouldn't be too hard to figure out. Here is a suggestion from top of my head: Find the center of mass of the "before"-points. Order the points according to their distance from this point. Now do the same with the "after"-points. The order of the two sets should now match. (The point closest to the center of mass before rotation, should be the point closest to the center of mass after rotation.)
It would be crazy overkill for this type of problem, but I think the functionality of the generalized Hough transform for object detection at least encompasses what you want, even though it's not quite meant for this purpose.
Given an arbitrary shape created from a set of points, and another arbitrary set of points, it tries to find the shape in the set of the points even though it's been rotated, scaled, and translated. You might be able to take out the scaling and translation and get what you want.
Basically what it would come down to is brute forcing possible rotation points to see which one fit the second set of points best.
Very interesting problem. My knowledge on this is a bit out of date, but as I recall, there's some research in the use of subgraph analysis on this; that is, characterizing subsections of the set of points by the distances between the points and the variances therein, and then correlating those subgraph analyses between the before and after rotations.
This is, of course, assuming a very complex set of points with a nonuniform distribution.
You need to find some signature on your data set that allows to identify the points from the first set (A) with those on the second set (B).
An easy way is as follows:
For every element E in A, find the two nearest points (N1, N2) and calculate the angle between N1,E,N2 resulting in three values: the angle and the distances from E to N1 and N2 (ang, d1, d2).
Find 3 points in A with unique tuples (ang, d1, d2).
For every element in B calculate also the distance to its two nearest neighbors and the angle. Find the 3 points matching those selected from A.
Calculating the rotation is just a matter of geometric analysis.
update: you need 3 points to determine the rotation in 3D space. In 2D, two will do.
update 2: as others have commented on other posts, there may be symmetries in A that would stop you for finding the 3 unique triplets for (ang, d1, d2). In that case, for every one of the selected three points in A, you will have to perform a search over all the elements in B matching their triplets until some combination results in a rotation that works for all the elements in A.

Resources