Sudoku solver, special case solving - java

I'm working on a sudoku solver with recursive backtracking which is pretty much finished except for one thing. If I would put duplicates somewhere within the puzzle (For example 1,1 in the top corner) it can go on forever trying to find a solution even though it's not a solvable puzzle.
Any help is greatly appreciated!
Rob

Well the way you know to backtrack is when your puzzle hits a contradictions, so at every step you should run a "validate" method, and if the puzzle is illegal then the last move that you made was illegal.
When you find that your move is illegal you can recursively backtrack and keep going.
Also, note that this is the rather naive approach, maybe some sudoku experts have a better algorithm, but this brute force should do the trick.

You want to detect an invalid situation, so you should check for it even before calling your solver. Your solver on itself will not create invalid solutions...

Regarding duplicates, i would suggest to keep a list of possible numbers for each cell, and when you are trying to solve a cell, you would compare this list against matching row, column and box, that way you will prevent creating duplicates. With this you can solve easier puzzles without backtracking. And if you get stuck, then use backtracking to continue...

This isn't necessarily the answer but it should help you. I have done this sort of thing before for a macro program and it was the highest rated one available.
A Sudoku solver can be quite a challenge. The only way to tell if a move is right is if it is absolute or if it is proved later on. This can lead to be quite a challenge as the end is based off of the current situation and moves. This means that you can handle this as a permutation. You can go through each square and figure out what possible numbers it has. From there, you could get one or two defined squares. Based off of this, there are many possible ways to get to an end point.
An 'end point' would be defined when the puzzle is solved (no errors - every square filled) or there is a fault.
Based off of this, you can treat each move as a node then build a tree system surrounding the possible moves.
For example:
8 7 1 2 _ _ 6 9 3
2 9 6 3 8 7 1 _ _
This is just a small example, but based off of it, respectively sweeping through each row, then each column we can generate possible numbers:
(5, 1) -> [4, 5]
(6, 1) -> [4, 5]
(8, 2) -> [4, 5]
(9, 2) -> [4, 5]
Based off of this, and the solutions given to us, we can see that there is exactly 4 possible solutions:
8 7 1 2 4 5 6 9 3
2 9 6 3 8 7 1 4 5
-or-
8 7 1 2 5 4 6 9 3
2 9 6 3 8 7 1 4 5
-or-
8 7 1 2 4 5 6 9 3
2 9 6 3 8 7 1 5 4
-or-
8 7 1 2 5 4 6 9 3
2 9 6 3 8 7 1 5 4
Though that is not enough information to solve the whole puzzle and figure out which is 'correct', this can be standardized and used to create a similar system and soon find a solution.
So you could add all 4 of these possibilities to a tree, each branching from the original:
8 7 1 2 _ _ 6 9 3
2 9 6 3 8 7 1 _ _
and then deal with them recursively.
Hope this helps!

To implement the Validate class, couldn't you just write Validate.validate(); inside of your solve method? Hope it helps.

Related

Order Crossover (OX) - genetic algorithm

Can someone explain me how Order Crossover works? I will give this example and I want to understand it in a generic way to implement after.
Parent 1 = 1 2 3 | 4 5 6 7 | 8 9
Parent 2 = 4 5 2 | 1 8 7 6 | 9 3
and the solution are two childreen:
Children 1 = 2 1 8 | 4 5 6 7 | 9 3
Children 2 = 3 4 5 | 1 8 7 6 | 9 2
I understand some parts but others not.
Thanks
Basically, a swath of consecutive alleles from parent 1 drops down, and remaining values are placed in the child in the order which they appear in parent 2.
Step 1: Select a random swath of consecutive alleles from parent 1. (underlined)
Step 2: Drop the swath down to Child 1 and mark out these alleles in Parent 2.
Step 3: Starting on the right side of the swath, grab alleles from parent 2 and insert them in Child 1 at the right edge of the swath. Since 8 is in that position in Parent 2, it is inserted into Child 1 first at the right edge of the swath. Notice that alleles 1, 2 and 3 are skipped because they are marked out and 4 is inserted into the 2nd spot in Child 1.
Step 4: If you desire a second child from the two parents, flip Parent 1 and Parent 2 and go back to Step 1.
One such solution for Ordered Crossover is detailed in this post.
This answer provides some sample java code with documentation detailing the processes used for the Ordered Crossover.
Additionally, this paper from Moscato provides a breakdown of the OX Process.
Hope this helps!

Generate all paths/routes through 2D array in Java

I'm working in Java. Given a matrix NxM, I need to find all possible paths through the array. It is only allowed to go diagonally up or down, or go to the right. An example 4x4 matrix:
3 5 7 9
2 4 6 8
9 3 7 5
6 8 2 4
The numbers in the matrix can be any arbitrary value. I would like to generate all possible routes through the matrix, starting in one of the four numbers in the first column. It is only allowed to move Northeast, East, and Southeast. An example route:
3-5 7 9
\
2 4 6-8
9 3 7 5
6 8 2 4
So all routes consist of M numbers. I'm using a 2D array to hold this NxM matrix. Some more possible paths are:
3 4 6 5
3 5 6 9
9 4 7 4
9 3 6 9
Is there a way to easily generate all paths in Java?
Any help is much appreciated!
Probably you can use three methods for doing this and call them recursively.
goNortEast(); Search for an element to the index [N-1][M+1] if N>0, else there will be no element NOrtEast of the current element, if element exists this will also lead to a new path.
goEast(); Each element can go East by index [N][M+1];
goSouthEast(); Search for element at index [N+1][M+1] if the element exists, this will also lead to a new path,
Call these three methods on each element starting from [0][0], then [1][0] and so on.
for [0][0], it will call goNorthEast[]- will not satisfy condition goEast();-index[0][1] and goSouthEast(); index[1][1] now call the same three methods of these elements.
At the end you will get all possible paths from the element you started.

Implementing "Full-Bin Packing" Algorithm in Java

I'm working on a project which is implementing the "Full-bin packing" algorithm in Java. This algorithm name comes from Decision A-Level Maths - but I can't find much information about it on the internet.
The algorithm is described as follows:
Use observation to find items that will fill a bin. Pack those items first.
Use the first-fit algorithm (which I have already written the methods for) to pack the rest of the items.
So I had 2 questions:
Is this the same as what is called "best-fit" algorithm?
How can I implement this in a program? (specifically, what is the best way of finding combinations that will fill a bin?)
In the case of my program, the items are going to be numbers and both the maximum number of numbers and the number of bins is going to be limited to 6.
I haven't actually written any code yet as I'm not sure about how to implement it in the first place - but I edited the first post to show one way I was thinking of doing it.
Edit -
Let's say the 6 numbers I have are: {1, 2, 3, 4, 5, 6}.
The way I thought of it was to first sort the numbers into decreasing order, and then having 2 loops to try every possible combination to see if any of them fill a bin (e.g. 1 & 2, 1 & 3, 1 & 4, 1 & 5, 1 & 6 and then 2 & 3, 2 & 4 and so on), would this be a good way of doing it?

Courier delivery with A* algorithm

I have to make a program which can calculate the shortest path to finish all deliveries.
The map is represent as x, y coordinate and the path is calculated using Manhattan distance(so go along x and then along y).
Start point is always (0, 0) and the courier can finish on any point. The courier can only bring 1 packet at any given time.
This could be implemented using A* search algorithm, my question is since A* algorithm is an I formed search, it needs to know heuristic value of its statusNode. What is a good heuristic implementation for this problem? Or even an idea for the heuristic value?
I have a sample input:
Job 3 3 to 5 3 # there is a job from (3,3) to (5,3)
Job 1 1 to 9 2 # there is a job from (1,1) to (9,2)
Job 3 5 to 2 7 # there is a job from (3,5) to (2,7)
Job 5 5 to 5 7 # there is a job from (5,5) to (5,7)
ANd the output:
Cost = 31
Move from 0 0 to 1 1
Carry from 1 1 to 9 2
Move from 9 2 to 3 3
Carry from 3 3 to 5 3
Move from 5 3 to 5 5
Carry from 5 5 to 5 7
Move from 5 7 to 3 5
Carry from 3 5 to 2 7
My current method for the search is:
I have list of jobToBeDone and jobDone
Intialise intial value of current position is 0, 0
Check whether all jobs have been done
If not, for all remaining jobs, Calculate the total cost=path to get there + some heuristic value of the job.
Put them in jobsToBeDone and sort with shortest path has lower index (like a priorityQueue in java).
repeat instruction from no 2 by updating current position to the job in the first index.
There are two problems. Shortest path and traveling salesman.
You need to calculate all paths between your points and then order the points to get the final shortest route. For the last part you need an heuristic or brute force for a small amount of points.
Instead of A* use Dijkstra as with dijkstra you can easily calculate several paths at once (as it is one to many)

Help:Graph contest problem: maybe a modified Dijkstra or another alternative algorithm

I'm trying to do this contest exercise about graphs:
XPTO is an intrepid adventurer (a little too temerarious for his own good) who boasts about exploring every corner of the universe, no matter how inhospitable. In fact, he doesn't visit the planets where people can easily live in, he prefers those where only a madman would go with a very good reason (several millions of credits for instance). His latest exploit is trying to survive in Proxima III. The problem is that Proxima III suffers from storms of highly corrosive acids that destroy everything, including spacesuits that were especially designed to withstand corrosion.
Our intrepid explorer was caught in a rectangular area in the middle of one of these storms. Fortunately, he has an instrument that is capable of measuring the exact concentration of acid on each sector and how much damage it does to his spacesuit. Now, he only needs to find out if he can escape the storm.
Problem
The problem consists of finding an escape route that will allow XPTO to escape the noxious storm. You are given the initial energy of the spacesuit, the size of the rectangular area and the damage that the spacesuit will suffer while standing in each sector.
Your task is to find the exit sector, the number of steps necessary to reach it and the amount of energy his suit will have when he leaves the rectangular area. The escape route chosen should be the safest one (i.e., the one where his spacesuit will be the least damaged). Notice that XPTO will perish if the energy of his suit reaches zero.
In case there are more than one possible solutions, choose the one that uses the least number of steps. If there are at least two sectors with the same number of steps (X1, Y1) and (X2, Y2) then choose the first if X1 < X2 or if X1 = X2 and Y1 < Y2.
Constraints
0 < E ≤ 30000 the suit's starting energy
0 ≤ W ≤ 500 the rectangle's width
0 ≤ H ≤ 500 rectangle's height
0 < X < W the starting X position
0 < Y < H the starting Y position
0 ≤ D ≤ 10000 the damage sustained in each sector
Input
The first number given is the number of test cases. Each case will consist of a line with the integers E, X and Y. The following line will have the integers W and H. The following lines will hold the matrix containing the damage D the spacesuit will suffer whilst in the corresponding sector. Notice that, as is often the case for computer geeks, (1,1) corresponds to the upper left corner.
Output
If there is a solution, the output will be the remaining energy, the exit sector's X and Y coordinates and the number of steps of the route that will lead Rodericus to safety. In case there is no solution, the phrase Goodbye cruel world! will be written.
Sample Input
3
40 3 3
7 8
12 11 12 11 3 12 12
12 11 11 12 2 1 13
11 11 12 2 13 2 14
10 11 13 3 2 1 12
10 11 13 13 11 12 13
12 12 11 13 11 13 12
13 12 12 11 11 11 11
13 13 10 10 13 11 12
8 3 4
7 6
4 3 3 2 2 3 2
2 5 2 2 2 3 3
2 1 2 2 3 2 2
4 3 3 2 2 4 1
3 1 4 3 2 3 1
2 2 3 3 0 3 4
10 3 4
7 6
3 3 1 2 2 1 0
2 2 2 4 2 2 5
2 2 1 3 0 2 2
2 2 1 3 3 4 2
3 4 4 3 1 1 3
1 2 2 4 2 2 1
Sample Output
12 5 1 8
Goodbye cruel world!
5 1 4 2
Basically, I think we have to do a modified Dijkstra, in which the distance between nodes is the suit's energy (and we have to subtract it instead of suming up like is normal with distances) and the steps are the ....steps made along the path. The pos with the bester binomial (Energy,num_Steps) is our "way out".
Important : XPTO obviously can't move in diagonals, so we have to cut out this cases.
I have many ideas, but I have such a problem implementing them...
Could someone please help me thinking about this with some code or, at least, ideas?
Am I totally wrong?
Since this is a contest problem, I'll just give a small hint:
In this example, it's the nodes that have weight, not the edges. One way of converting such a graph to the usual kind is to replace each node with two nodes, an in node and an out node, and a directed edge from in to out with weight equal to the original node's weight. Then for each directed edge in the original graph, put a directed edge from the out node of one to the in node of the next.
Your idea sounds good - go with it.
By the way, when working these problems, try to work out the implementation for yourself. It rarely helps to simply see someone else's implementation. Ask for help on the algorithm if you need to, but implement it yourself.
You don't have to treat this with any unconventional conversions like you said (subtracting instead of adding, etc).
The shortest path from one node to another is one that minimizes the total damage to the suit along the way, regardless of whether or not this journey will kill you.
Just find the shortest path from START to EXIT, summing up edge weights as is usual Dijkstra approach, and then consider if this shortest path is feasible for the given suit power. If it isn't, then Goodbye cruel world!.
If you insist on pruning the search once you know that you can definitely not reach the EXIT, then adding it after the above implementation is trivial: as you're expanding your search horizon in your Dijkstra search, if even going to the next closest node to expand from kills you, then the rest of search space also will, so you can just abort and Goodbye cruel world!.
As for the graph itself, conceptually this is what you want. The vertices of the directed graph consists of all nodes in the grid, plus an artificial EXIT node.
All edge nodes have a directed edge to EXIT; the weight of these edges is 0
All neighboring (non-diagonal) node have directed edges between them
From node n1 to n2, the weight of the edge (i.e. the cost damage of travelling from n1 to n2) is the damage incurred by staying at node n2 (let's call this damageAt[n2], which you get from D matrix in input).
So minimum total amount of damage that one must sustain to go from START to EXIT is damageAt[START] + costOf(shortestPathBetween(START, EXIT)).
In summary, this approach:
Only requires standard Dijkstra implementation
Requires only very small modification to add pruning
Requires only very simple transformation from the input grid to the directed graph

Categories