i have a matrix
1 9 2 3
5 0 0 6
8 4 4 8
2 3 7 8
I need to find all possible combinations of numbers of length 5.
constraints:
-
Starting form a any position in the matrix you can only move to your next immediate neighbor i.e if u start form say (0,0) your neighbor must be (0,1),(1,1),(1,0) and if you pick a position then form that position you can only move to its immediate neighbor and so on.
-
The length of the number must be 5 digit’s i.e for example if i start from (0,0) with value 1 i can produce a sequence 15151 or 19232 or 10063 so on you can move in any sequence with the constraint 1 applied.
-
The solution must produce the output in 7sec and python is preferred since its my favorite. 😉
OK i missed some things the program must use all 16 numbers i.e it must use all the 16 numbers as initial and produce the 5 digit sequence.
First, you have to think about how to start at one position in the matrix and move to an adjacent one.
The brute force method is simply to list all available cells and all adjacent cells for each:
For a problem this small, this is pretty simple; however, there is always a chance of typos. Another solution is to write a generator function:
Once we know which cells are next to each other, we can proceed to seek valid paths:
We can find out how long this takes by profiling:
which returns
This returns a list of lists of cell-positions; we want to turn this into the actual values from the matrix,
Then
We also want to reduce the list to unique results:
which gives us