Find path of specific length between point A and B on grid - unity3d

I'm working on a game that will always be an n x n grid. I'd like to be able to always generate a new start position from the outer edge and have a path to the center cell. My issue is that I want to be able to specify the path length instead of choosing the shortest path. Does anyone have an idea of how to do this?
I've looked at several CompSci forums, but unfortunately I'm unable to make heads or tails of what they're saying.
https://cs.stackexchange.com/questions/44401/what-algorithm-to-use-to-generate-random-path-of-given-length

In order to avoid the hardcore math, I would suggest to always use the shortest possible path and randomly generate and add some pieces to it to make it the length you want. It would not be absolute random, but for sure it should look good enough. Although it depends on your needs.

Related

Matlab - Flag points using nearest neighbour search

I have the following problem and I am a bit clueless how to tackle it as my programming skills are very elementary ( I am an engineer, so please dont bite my head off).
Problem
I have a point cloud, the picture above displaying one level off it. Every point is a centroid off a block (x =5, y=1, z=5) and is specefied by carteisian coordinates.
The centroids further have two values: one called "access" and one "product". If the product value is positive and pays for the access to the point I want to include it in my outcome. The red marker in the picture represents a possible starting point.
Starting Idea
As a start I am trying to set up an algorithm, that starts at the red marker, runs through the blocks left and right (along the x-axis), checks until where it would be feasible to access (so sum "product" > sum "access") and then goes to the next point (in y direction from marker) and does the same until the end of the level.
Final Goal
My final goal is that I can Flag points as accessed and the algorithm connects profitable "products" (so products that would pay for their access) on the shortest way to the access point (by setting blocks/points on the way to accessed).
I know this is a very open question and I apologize for that. I am just lacking a good starting point programming wise. I was thinking of knnsearch, but I am not sure if this is the right way to go as the blocks have different sizes and i technically want the nearest neighbour in every direction but also only one per direction.
Another idea I had was using shortestpath or creating a travel salesman problem out of it, but I am not sure how to properly implement it.
If you have any ideas or you could offer any help I would very much appreciate it. If any more information is needed I gladly provide it.

Hashing a graph to find duplicates (including rotated and reflected versions)

I am making a game that involves solving a path through graphs. Depending on the size of the graph this can take a little while so I want to cache my results.
This has me looking for an algorithm to hash a graph to find duplicates.
This is straightforward for exact copies of a graph, I simply use the node positions relative to the top corner. It becomes quite a bit more complicated for rotated or even reflected graphs. I suspect this isn't a new problem, but I'm unsure of what the terminology for it is?
My specific case is on a grid, so a node (if present) will always be connected to its four neighbors, north, south, east and west. In my current implementation each node stores an array of its adjacent nodes.
Suggestions for further reading or even complete algorithms are much appreciated.
My current hashing implementation starts at the first found node in the graph which depends on how i iterate over the playfield, then notes the position of all nodes relative to it. The base graph will have a hash that might be something like: 0:1,0:2,1:2,1:3,-1:1,
I suggest you do this:
Make a function to generate a hash for any graph, position-independent. It sounds like you already have this.
When you first generate the pathfinding solution for a graph, cache it by the hash for that graph...
...Then also generate the 7 other unique forms of that graph (rotated 90deg; rotated 270deg; flipped x; flipped y; flipped x & y; flipped along one diagonal axis; flipped along the other diagonal axis). You can of course generate these using simple vector/matrix transformations. For each of these 7 transformed graphs, you also generate that graph's hash, and cache the same pathfinding solution (which you first apply the same transform to, so the solution maps appropriately to the new graph configuration).
You're done. Later your code will look up the pathfinding solution for a graph, and even if it's an alternate (rotated, flipped) form of the graph you found the earlier solution for, the cache already contains the correct solution.
I spent some time this morning thinking about this and I think this is probably the most optimal solution. But I'll share the other over-analyzed versions of the solution that I was also thinking about...
I was considering the fact that what you really needed was a function that would take a graph G, and return the "canonical version" of G (which I'll call G'), AND the transform matrix required to convert G to G'. (It seemed like you would need the transform so you could apply it to the pathfinding data and get the correct path for G, since you would have just stored the pathfinding data for G'.) You could, of course, look up pathfinding data for G', apply the transform matrix to it, and have your pathfinding solution.
The problem is that I don't think there's any unambiguous and performant way to determine a "canonical version" of G, because it means you have to recognize all 8 variants of G and always pick the same one as G' based on some criteria. I thought I could do something clever by looking at each axis of the graph, counting the number of points along each row/column in that axis, and then rotating/flipping to put the more imbalanced half of the axis always in the top-or-left... in other words, if you pass in "d", "q", "b", "d", "p", etc. shapes, you would always get back the "p" shape (where the imbalance is towards the top-left). This would have the nice property that it should recognize when the graph was symmetrical along a given axis, and not bother to distinguish between the flipped versions on that axis, since they were the same.
So basically I just took the row-by-row/column-by-column point counts, counting the points in each half of the shape, and then rotating/flipping until the count is higher in the top-left. (Note that it doesn't matter that the count would sometimes be the same for different shapes, because all the function was concerned with was transforming the shape into a single canonical version out of all the different possible permutations.)
Where it fell down for me was deciding which axis was which in the canonical case - basically handling the case of whether to invert along the diagonal axis. Once again, for shapes that are symmetrical about a diagonal axis, the function should recognize this and not care; for any other case, it should have a criteria for saying "the axis of the shape that has the property [???] is, in the canonical version, the x axis of the shape, while the other axis will be the y axis". And without this kind of criteria, you can't distinguish two graphs that are flipped about the diagonal axis (e.g. "p" versus "σ"/sigma). The criteria I was trying to use was again "imbalance", but this turned out to be harder and harder to determine, at least the way I was approaching it. (Maybe I should have just applied the technique I was using for the x/y axes to the diagonal axes? I haven't thought through how that would work.) If you wanted to go with such a solution, you'd either need to solve this problem I failed to solve, or else give up on worrying about treating versions that are flipped about the diagonal axis as equivalent.
Although I was trying to focus on solutions that just involved calculating simple sums, I realized that even this kind of summing is going to end up being somewhat expensive to do (especially on large graphs) at runtime in pathfinding code (which needs to be as performant as possible, and which is the real point of your problem). In other words I realized that we were probably both overthinking it. You're much better off just taking a slight hit on the initial caching side and then having lightning-fast lookups based on the graph's position-independent hash, which also seems like a pretty foolproof solution as well.
Based on the twitter conversation, let me rephrase the problem (I hope I got it right):
How to compare graphs (planar, on a grid) that are treated as invariant under 90deg rotations and reflection. Bonus points if it uses hashes.
I don't have a full answer for you, but a few ideas that might be helpful:
Divide the problem into subproblems that are independently solvable. That would make
How to compare the graphs given the invariance conditions
How to transform them into a canonical basis
How to hash this canonical basis subject to tradeoffs (speed, size, collisions, ...)
You could try to solve 1 and 2 in a singe step. A naive geometric approach could be as follows:
For rotation invariance, you could try to count the edges in each direction and rotate the graph so that the major direction always point to the right. If there is no main direction you could see the graph as a point cloud of its vertices and use Eigenvectors and Priciple Compoment Analysis (PCA) to obtain the main direction and rotate it accordingly.
I don't have a smart solution for the reflection problem. My brute force way would be to just create the reflected graph all the time. Say you have a graph g and the reflected graph r(g). If you want to know if some other graph h == g you have to answer h == g || h == r(g).
Now onto the hashing:
For the hashing you probably have to trade off speed, size and collisions. If you just use the string of edges, you are high on speed and size and low on collisions. If you just take this string and apply some generic string hasher to it, you get different results.
If you use a short hash, with more frequent collisions, you can get achieve a rather small cost for comparing non matching graphs. The cost for matching graphs is a bit higher then, as you have to do a full comparison to see if they actually match.
Hope this makes some kind of sense...
best, Simon
update: another thought on the rotation problem if the edges don't give a clear winner: Compute the center of mass of the vertices and see to which side of the center of the bounding box it falls. Rotate accordingly.

Drawing a polygon by a lot of dots

My desired output is moving a lot of dots to visualize some words.
The effect is similar to this video http://www.youtube.com/watch?v=Le13by2WM70 .
I think this problem could be split into two sub-problem.
The first is how to extract the path from a vector font.
The second is how to moving dots to visulize that polygon.
There are some tools could solve first part, but I have not idea about the second part.
Anyone has done this?
You could probably do pretty well by just sampling points on a regular grid, with a little jitter added in to avoid looking too computery. All you need to do is check if you are "inside" or "outside" of the path. For inside, place a fish (or dot); for outside, no fish.

MatLab maze solving

I've been using the maze_solution function from Image Analyst http://www.mathworks.com/matlabcentral/fileexchange/27175-mazesolution for a while without problems. There are a few limitations: the maze has to be perfect and without circular paths.
That being said, it generally works very well when I test it, let me provide you with two examples of outputs:
maze-1 -> solution-1 (Clearly works well)
maze-2 -> solution-2 (Not so well)
Now let me put some rules that are not obvious about my mazes:
There are no circular paths (there are some that are trapped in the walls, but no one that the the maze solver would run into).
They begin always at the top left, and then there are four exits in the same coordinates every time.
There is always only one exit.
So, what I would like to do is, let's consider the first screenshot. It works well and 'finds' the exit, is there any way to make mat lab pop up a messagebox (using msgbox(), for instance) and say something like "Hey user, I found the solution! It's A!"? I already thought about this for a long while, but found no way of doing this. One of the solutions I thought about was, in pseudocode:
if CertainCoordinate = red pixel
return A
Whereas CertainCoordinate Could be the unchangeable coordinates (x and y) of A, B,C and D (Then I would use 4 'ifs'), but I don't really know how to implement even that. Any ideas or... something to point me in the right direction?
So, summarizing it: I have an algorithm that right now generates a red path to the exit (and I am open to better algorithms, if you have any suggestion) but my goal is to make matlab tell me what he found, instead of showing me in a image. So for instance, in the first image I would like it to open a MessageBox and say "Hey user! I found the exit, it's D!", instead of showing me the image with the red path on it. The problem is, I don't know how to teach MatLab 'where is D' and to make him recognize that he found 'D'. So, are there any suggestions on how to do that?
Thanks in advance!
Suppose you have an image called maze aset of possible x coordinates of the exit and the corresponding y coordinates of the exit. Also you can check what color the maze solving program uses, lets say this is Red.
Now the solution is quite simple. First run the maze solver, then check the following
isRed = maze(x,y) == Red;
exitxCoordinates = x(isRed)
exityCoordinates = y(isRed)
This gives you the x and y coordinates. (If no solution is found they are empty).
From here it should not be too hard to connect them to one of the letters that you specified.

Check if drawn path/CGPath intersects itself in an iPhone game

I have a path drawn in OpenGL ES. I can convert it to a CGPath if needed.
How would I check if it intersects itself (If the user created a complete loop)?
Graham Cox has some very interesting thoughts on how to detect the intersection of a CGPathRef and a CGRect, which is similar to your problem and may be educational. The underlying problem is difficult, and most practical solutions are going to be approximations.
You may also want to look at this SO article on CGPathRef intersection, which is also simliar to your problem, and some of the proposed solutions are in the same space as Graham's above.
Note: This answer is to an earlier version of the question, where I thought the problem was to determine if the path was closed or not.
I think a path is considered closed iff the current point == the starting point.
The easiest way I know of to check this is to keep track of these two points on your own, and check for equality. You can also use CGPathGetCurrentPoint, and only track the starting point to compare with this.
Here's a roundabout way to find the starting point, if it's hard to just keep track of it directly:
make a copy of the path
store its current point
call CGPathCloseSubpath
check to see if the current point changed
If it did change, the original path was open; otherwise closed.
This is a way to check if a path composed of a single continuous segment is self-intersecting.
I'm sure that if you wanted a faster implementation, you could get one by using some good thinking and full access to the CGPath internal data. This idea focuses on quick coding, although I suspect it will still be reasonably fast:
Basically, take two copies of the path, and fill it in two different ways. One fill uses CGContextEOFillPath, while the other uses CGContextFillPath. The results will be different iff the path is self-intersecting.
You can check if the result is different by blending the results together in difference blend mode, and testing if the resulting raw image data is all 0 (all black).
Hacky, yes. But also (relatively) easy to code.
** Addendum ** I just realized this won't work 100% of the time - for example, it won't detect a figure eight, although it will detect a pretzel.