I need some advise in an approach I may need to take to solve a gaming problem which is a puzzle (NxN), the puzzle consists of positive numbers and stored in a two dimensional array. For simplistic reasons is i´ll list a simple example
2 1 2 2
1 3 2 1
1 0 2 1
3 1 2 0
So the starting point is at (0,0) => 2 and the goal location is to (3,3) => 0
The number in the array location tells you how far to move. (0,0)=> 2 can move to either (0,2) or (2,0) and so on (moves allowed left, right, up, or down)
So you end up with a solution like this for example (0,2)=>(2,2)=>(2,0)=>(3,0)=>(3,3).
so my question is what sort of algorithm i should be looking into and whether any of you have done something similar to this?
You have plenty of solutions here:
A* algorithm
Dijkstra
Depth-first
Breadth-first
The first two will give you an optimal solution if one exists. A* is typically faster than Dijkstra if the heuristic is well chosen. Breadth- first will also give you an optimal implementation. Depth-first may give you non-optimal solutions in this problem.
The main difference between A* and Djisktra is that A* defines a heuristic, namely a function that tries to estimate if a move is better than another one.
The main difference between depth-first and breadth-first is the order in which they explore the space of solutions. Breadth-first will start by looking for all solutions of length 1 then all solutions of length 2, etc, while depth-first will fully explore an entire path until it either cannot go any further or finds a solution.
A* and Dijkstra are typically implemented in imperative style and are probably more sophisticated than the other two, especially A*. Breadth-first is also naturally expressed in imperative style. Depth-first is generally expressed recursively, which can be a problem if your solutions can exceed a length of several thousands moves (depending on the size of your stack, you will generally only be able to make 7-10k recursive calls before you get a StackOverflowError).
To sum up:
A* is generally the most efficient of the algorithms listed below
A* is the most difficult to implement
Dijkstra is a special case of A* with similar performance but potentially less efficient
Breadth-first is straightforward to implement and is resilient to long solutions
Depth-first is straightforward to implement but it is limited by the length of the longest possible path if it is implemented recursively
All these algorithms except depth-first guarantee an optimal solution
Code example:
I found this Scala implementation of A* in one of my repositories. Might help.
I have some grid search algorithms (Best-First, Breadth-First, Depth-First) implemented here in Object Pascal (Delphi), that you could easily adapt to Java if this was a classic grid search:
https://github.com/Zoomicon/GridSearchDemo/tree/master/Object%20Pascal/algorithms
You can try the GridSearchDemo application here to see how those algorithms behave when searching in a grid with start and target point and obstacles in various grid cells (you can set them):
https://github.com/Zoomicon/GridSearchDemo/releases
In general, I prefer the A* algorithm, which is an example of a Best-First algorithm (https://en.wikipedia.org/wiki/Best-first_search)
In your case, this is not a grid really, but a graph, since you seem to have jump links to other cells (or at least this is how you explain the number in your question, although you call it "how far" at first)
I have written a program in java to solve this problem. It uses A*-algorithm with heuristic functions Manhatten and hamming. It depends on the person whether he uses hamming or manhatten distance but Manhatten is better.
Here is my code in java: 8-puzzle
Btw it's not an easy approach and many problems can't be solved.
Related
Consider a problem similar to this: Ice Sliding Puzzle Path Finding
Except that I wish to find the optimal shortest path algorithm. I've looked into it and found that BFS, A* and Djikstra's are all viable algorithms, but I need some advice on which would be best for my scenario or if there's a better choice.
My scenario being where an ice maze similar to the one in the stackoverflow question exists and is in a txt file. For the data structure holding the grid I thought to use a 2D char array since I thought it would perform best but maybe simplicity isn't the way to go here.But I'm clueless as to whether more fitting data structures exist
With that taken into account which of the three algorithms do you guys think would perform best on one of these mazes given that they'd be say max 2560x250 in size with varying complexities in the possible paths.
Concerns with BFS - non-optimal path storage approach, considers each tile moved a step so one path could be sliding along step by step while another is taking steps in different directions with shorter slides ( don't know the performance impact it will have)
Concerns with A* & Dijkstra's - Forming all possible nodes and edges with weights could be a heavy process
simple example maze txt (0 - wall, S - Start, F - Finish)
.0...00...
.0F0......
..0..0....
.0.0.....0
..........
..........
....0.0.0.
.0.0......
0........0
S.0.....00
I've got a grid 9x9 squares. Those squares are written in array of integer.
so every integer represents 1 block. Integer provides enough bits for X,Y positions, if this block is accessible and other data. I have a problem: What would be the most effective way to get boolean value, if we can get from the center of this grid to some random point. So for example i provide X and Y positions for block where i want to go, and a method will return boolean value, if there is some way through ACCESSIBLE blocks. I made a simple picture for this. Thanks for answers.
What you're describing here is a well-known problem in computer science called pathfinding and not trivial to solve efficiently.
However, there are several algorithms to solve this, like A* and Dijkstra, which are probably the way to go for large, complicated maps.
If all of your problems are as small and simple as your posted example, you could also try to work with a simpler solution, like a brute force graph search, (as suggested by Codor).
The problem can be solved by depth-first search, where the specific implementation greatly depends on the representation of the grid, which is to be interpreted as a graph.
Let's say I want to build a function that would properly schedule three bus drivers to drive in a week with the following constraints:
Each driver must not drive more than five times per week
There must be two drivers driving everyday
They will rest one day each week (will not clash with other drivers' rest day)
What kind of algorithm would be used to solve a problem like this?
I looked through several sites and I found these:
1) Backtracking algorithm (brute force)
2) Genetic algorithm
3) Constraint programming
Frankly, these are all "culture shock" for me as I have never learnt any kind of linear programming in the past. There are two things I want to know:
1) Which algorithm will best suit the case scenario above?
2) What would be the simplest algorithm to solve this problem?
3) Please suggest any other algorithms I can look into to solve the above problem.
1) I agree brute force is bad.
2) Your Problem is an Integer Problem. They can be solved with Linear Programming though.
3) You can distinquish 2 different approaches: heuristics and exact approaches.
Heuristics provide good solutions in reasonable computation time. They are used when there are strict requirements on the computation time or if the problem is too hard to calculate an optimal solution. Genetic Algorithms is a heuristic.
As your Problem is comparably simple, you would probably go with an exact approach.
4) The standard way to solve this exacly, is to embed a Linear Program in a Branch & Bound search tree. There is lots of literature on it. The procedure can be outlined as follows:
Solve the Linear Program with the Simplex-Algorithm
Find a fractional variable for branching. I.e. x=1.5
Create two new nodes and add the constraints x<=1 and x>=2 respectively
Go into one node (selected by some strategy)
Go to point 1
Additionally, at every node in the tree, after point 1, the algorithms checks, if a node can be pruned. That means to stop searching 'deeper' from this node on, because
a) the problem has become infeasible,
b) a better solution already exists,
c) an integer solution is found. This objective value of this solution is used to determine point b.
The procedure finishes when all nodes are pruned.
Luckily, as Nicolas stated, there are free implementations that do just this. All you have to do is to create your model. Code its objective and constraints in some tool and let it solve.
First of all this is a discrete optimization problem, so linear programming is probably not a good idea (since it is meant for continuous optimization). You can still solve this using linear programming (it will become an integer or mixed-integer program) but that is exponentially heard (if your input size is small then it is ok).
Now back to the comparison:
Brute force : worst.
Genetic: Can not guarantee optimality. The algorithm may not be able to solve the problem.
Constraint programming: definitely the best in this case (and in many discrete optimization problems). There is a super efficient implementation of it in IBM ILOG CPLEX solver (but is is not free, it is free for academia or for testing though).
I'm making a robot maze in java in which the robot uses the depth-first search algorithm to traverse the maze and reach the target. This works fine in a maze with no loops, but when those are introduced the algorithm fails. Is there any way to make depth-first search work with loopy mazes? If so, how does one go about doing that?
I have two separate implementations of this maze - one records each junction and stores it in an array while the other one uses a stack to push a new junction and pop it off when it has finished exploring that junction. A solution using any one of these implementations is acceptable.
You need to mark visited nodes and treat them as "additional" walls.
That way, you can avoid searching loops. It will no longer find the shortest path though.
See Dijkstra's algorithm for details. For an even more advanced - directed - version, look at A* search. On difficult mazes, it shouldn't gain you a lot though. A* is more interesting for open areas.
I am designing a flight simulation program and I am looking for ideas on how to properly
implement such requirement.
Kindly look at my picture below. The points represents location.
The idea is this, I wanted to properly create a data structure to best represent such scenario
in java such that
when I am in Point 1, how far I am from the last point which is Point 8?
Points 2, 3 and 5 are at the same distance from Point 8
From Point 1, I could traverse to Point 3 to Point 6 then 7 then eight that would equate to 4 Steps.
when I am in Point 0
I could traverse to Point 4 then 5 then 7 then reach point 8 which would equate to 4 steps also.
I just wanted to assist user to help them find different route.
Is this possible and which java data structure should best fit this requirement? Also any design ideas how to implement this?
Sorry if my question might be vague, I am just trying to get as much information as I can to properly handle such requirement.
What you have is a weighted graph where the weights represent the distance between the nodes (which is very common). You could easily implement this yourself (and it's a great way to learn!), but there are lots of java source code for this out there.
Of course, this is not a java data structure. It's simply a data structure (or a concept), used by everyone, everywhere.
Calculating steps and distances is very easy once you've implemented a weighted graph.
There are massive amounts of documentation on all of this, especially here on Stackoverflow.
This is a Shortest Path problem, a common Graph problem. The usual way to represent the data is an Adjancency List or Matrix:
An adjancency list keeps, for every node, all 1-step reachable destinations. This is often implemented as a Linked List. It's the proper choice if your graph is relatively sparse (i.e. few destinations per node).
An adjancency matrix is used for (very) dense graphs. Basically, you keep an NxN matrix of values (weights/costs, or yes/no booleans). Then, distances[i][j] represents the cost of travelling to j from i. An unavailable arc has a cost of INF (or some error value).
The problem itself is generally solved by Dijkstra's Algorithm.