Generate all paths/routes through 2D array in Java - 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.

Related

smallest possible sum of the values of subarrays

I'm trying to understand question and solving it using java.
But first I'm not able to understand properly.
Here is the question:
You are given an array a of length n and an integer c.
The value of some array b of length k is the sum of its elements except for the smallest. For example, the value of the array [3, 1, 6, 5, 2] with c = 2 is 3 + 6 + 5 = 14.
Among all possible partitions of a into contiguous subarrays output the smallest possible sum of the values of these subarrays.
Input
The first line contains integers n and c (1 ≤ n, c ≤ 100 000).
The second line contains n integers ai (1 ≤ ai ≤ 109) — elements of a.
Output
Output a single integer — the smallest possible sum of values of these subarrays of some partition of a.
Examples
inputCopy
3 5
1 2 3
output
6
inputCopy
12 10
1 1 10 10 10 10 10 10 9 10 10 10
output
92
inputCopy
7 2
2 3 6 4 5 7 1
output
17
inputCopy
8 4
1 3 4 5 5 3 4 1
output
23
In the third example one of the optimal partitions is [2, 3], [6, 4, 5, 7], [1] with the values 3, 13 and 1 respectively.
My Understanding:
1) Partition is being being done within continuous numbers. Correct ?
2) What is the significance of Integer c in input ?
3) How is being done in third example ? I mean after having subarrays, How 13 came out from second subarray ?
Can anyone help me to understand the question ? I can write code myself.

How to print all possible sequences with intermixed sequence of push and pop operation

Suppose that an intermixed sequence of push and pop operations are performed on a LIFO stack.How to print all possible sequences? I can just judge it's about recursion. For example, if order 1 2 3 is given, output is
1 2 3
1 3 2
2 1 3
2 3 1
3 2 1
Use Google GUAVA's method https://google.github.io/guava/releases/19.0/api/docs/com/google/common/collect/Collections2.html#orderedPermutations(java.lang.Iterable) to get all possible permutations and then for each permutation reverse the order using https://docs.oracle.com/javase/7/docs/api/java/util/Collections.html#reverse(java.util.List)

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)

Sudoku solver, special case solving

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.

Multithreaded search of single collection for duplicates

use I can't divide into segads. As for my above example if 5 threads are set, then first segment would take 2 first object, and second 3th and 4th, so they dont find dups, but there are dups if we merge them, its 2th and 3th.
There could be more complex strate take from first threads .. ah nevermind, to hard to explain.
And ofcourse, problelection itself in my plans.
Tha
EDIT:
InChunk, and then continue analyzing that chunk till the end. ;/
I think the process of dividing up the items to be de-duped is going to have to look at the end of the section and move forward to encompass dups past it. For example, if you had:
1 1 2 . 2 4 4 . 5 5 6
And you dividing up into blocks of 3, then the dividing process would take 1 1 2 but see that there was another 2 so it would generate 1 1 2 2 as the first block. It would move forward 3 again and generate 4 4 5 but see that there were dups forward and generate 4 4 5 5. The 3rd thread would just have 6. It would become:
1 1 2 2 . 4 4 5 5 . 6
The size of the blocks are going to be inconsistent but as the number of items in the entire list gets large, these small changes are going to be insignificant. The last thread may have very little to do or be short changed altogether but again, as the number of elements gets large, this should not impact the performance of the algorithm.
I think this method would be better than somehow having one thread handle the overlapping blocks. With that method, if you had a lot of dups, you could see it having to handle a lot more than 2 contiguous blocks if you were unlucky in the positing of the dups. For example:
1 1 2 . 2 4 5 . 5 5 6
One thread would have to handle that entire list because of the 2s and the 5s.
I would use a chunk-based division, a task queue (e.g. ExecutorService) and private hash tables to collect duplicates.
Each thread in the pool will take chunks on demand from the queue and add 1 to the value corresponding to the key of the item in the private hash table. At the end they will merge with the global hash table.
At the end just parse the hash table and see which keys have a value greater than 1.
For example with a chunk size of 3 and the items:
1 2 2 2 3 4 5 5 6 6
Assume to have 2 threads in the pool. Thread 1 will take 1 2 2 and thread 2 will take 2 3 4. The private hash tables will look like:
1 1
2 2
3 0
4 0
5 0
6 0
and
1 0
2 1
3 1
4 1
5 0
6 0
Next, thread 1 will process 5 5 6 and thread 2 will process 6:
1 1
2 2
3 0
4 0
5 2
6 1
and
1 0
2 1
3 1
4 1
5 0
6 1
At the end, the duplicates are 2, 5 and 6:
1 1
2 3
3 1
4 1
5 2
6 2
This may take up some amount of space due to the private tables of each thread, but will allow the threads to operate in parallel until the merge phase at the end.

Categories