Can someone introduce me to the Hamiltonian Cycle? - java

I have this project where I have to come up with Java source code implementing the Hamiltonian cycle.
I searched on google and at least now I know what a Hamiltonian cycle is, path that passes through all vertices just once except the starting vertex because it's also the last vertex (tell me if I'm wrong).
The problem is I don't know how to implement it. Basically, my questions are:
How, where do you implement a Hamiltonian cycle?
What is the application of a Hamiltonian Cycle (so that it helps to understand why it's so important)

You don't implement a Hamiltonian cycle, you find it (or find out that none exists for your given graph). Since this is an NP-complete problem, which means this is probably no efficient solution, I'd just implement a simple backtracking algorithm. Since you're looking for a cycle, it does not matter at which node you start.
Hamiltonian cycles can be used in cryptography for zero-knowledge proofs.
I'm not sure whether this is still just research or whether it's being actively used in any cryptographic protocol.

Is this homework? If so please tag it as such.
It is easy to implement it if you can use recursion (not the case if the graph gets too large). What you do is write a function that takes as argument the graph (there are different representations for this), the function checks whether the graph consists of only the starting-point, if so it returns, if it didnt return it calls itself recursively for each node N that is still in the graph and gives the graph minus the node N as arguments.

The simplest way is to start with one node, "tag it", choose the next reachable "untagged" node, "tag it", and continue until either:
you reach the starting node, thus you found Hamiltonian cycle. Repeat the cycle for every node to find each and every Hamiltonian cycle in that graph.
You cannot choose another "untagged" node, which means that there is no Hamiltonian cycle for that starting node (but you found a Hamiltonian Path, anyway).
That algorithm can be optimized in several ways, but I let you that to you. Any solution you find will be NP-complete.
As for they uses, I only saw them in Graph theory and AI classes (this is a particular travelsman problem, where each edge has a cost of 1) and they never told me real-life uses for that.

(B) Practical Application
Determining most efficient switching network for phone systems
Best bus routes, postal routes, meter checking routes

Related

Java Path-finding puzzle game

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.

How can I influence minimax algorithm to prefer immediate rewards?

I am implementing the minimax for a Stratego game (where the computer has perfect knowledge of all the pieces). However, I find that the computer will often not attack a piece that it can easily destroy. From what I understand, the minimax scores comes from the leaf nodes of a move tree (where each level is a turn and each score for the leaf node is calculated using an evaluation function for the board in that position). So if I have a depth of 3 levels, the computer can choose to attack on move 1 or attack on move 3. According to the minimax algorithm, it has the same score associated with it (the resulting board position has the same score). So how do I influence the minimax algorithm to prefer immediate rewards over eventual rewards? i.e. I would like the score to decay over time, but with the way minimax works I don't see how this is possible. Minimax always uses the leaf nodes to determine the intermediate nodes.
As mentioned by others in the comments, minimax should be able to notice if there is a danger in delaying to capture a piece automatically, and changing the evaluation function to force it to prefer earlier captures is likely to be detrimental to playing performance.
Still, if you really want to do it, I think the only way would be to start storing extra information in your game states (not only the board). You'll want to store timestamps in memory for every game state which allow you to still tell in hindsight exactly at what time (in which turn) a piece was previously captured. Using that information you could implement a decay factor in the evaluation function used in leaf nodes of the search tree.
A different solution may be to simply make sure that you search to an even depth level; 2 or 4 instead of 3. That way, your algorithm will always evaluate game states where the opponent had the last move, instead of your computer player. All evaluations will become more pessimistic, and this may encourage your agent to prefer earlier rewards in some situations.
This effect where odd search depths typically result in different evaluations from even search depths is referred to as the odd-even effect. You may be interested in looking into that more (though it's typically discussed for different reasons than what your question is about).

Finding all paths though a graph. Is it possible (how?) to create an iterator of results, and would it be more efficient?

Lets say I have a graph and a starting node. Each note has a weight.
The problem is to find all paths from the starting node where the sum of weights of the nodes are, say, five.
A simple approach is to do a depth first search, and, on discovering the sum of the current path is five, you could simply copy the solution into a list of solutions.
This simply solution would require you to search the entire tree until there are no more possibilities. What if you only needed one solution? Or two? Or the best out of 100? Wouldn't this approach waste potentially a large amount of memory storing all solutions?
I imagine you could write some sort of Iterator, where .next() simply continues the search until it finds a new path. This way you waste no storage or computation time.
I figured I'd ask if such a known pattern, or solution, or algorithm exists before trying to reinvent the wheel.
Additionally:
My actual problem is a special Iterator which finds all trees matching a certain condition, but I assumed the answer to the more general path problem would lead me closer to the solution to my problem. Any information on this would also be very much appreciated.
You could simply pass around a count in your function and return when you've reached that count.
void dfs(List<...> solutions, int count, ...)
{
// check for solution and add to solutions
if (solutions.size() == count)
return;
...
dfs(solutions, count, ...);
if (solutions.size() == count)
return;
...
}
This is probably the solution requiring the least changes (C# has functionality that allows you to have "some sort of Iterator, where .next() simply continues the search until it finds a new path", but Java doesn't, to my knowledge).
Alternate solutions are:
Have multiple threads. Let one thread run your function, adding items to a global list. Let another thread access this list and presumably add some functionality to have the one running your function stop after adding an element to the list, and let the other thread resume it, or something like that.
If you're using a recursive function, convert this to an iterative one, and store the Stack in a class variable after generating a single solution, and return, allowing you to continue again.
There exists an algorithm used to solve exactly your problem.
It is called the Djikstra's Algorithm and is used to solve shortest path node problems.
You can find codes of it on the web, and probably learn more as well.
Wikilink

Existing Algorithm for Scheduling Problems?

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).

Depth first search with loops

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.

Categories

Resources