I have a 9x9 matrix, each element of which is a list of one to five numbers (integers) between one and nine . (“Dimensions” shows 9,9. Why, if each element is a list?). I am trying to find the Position(s) of all those elements in the matrix with one (or two, or three) number(s) in them. “Length” doesn’t work with more than one list (matrix element). I know I can do this with a loop, but hope there is a more elegant way.
(Have you guessed that I am trying to program a solution to Sudoku puzzles as a learning exercise?)
Hi,
if I understand correctly this should do the trick.
First I generate a matrix which is -hopefully- of the form you want to test my algorithm:
matrix = Table[Table[RandomInteger[8] + 1, {m, 1, RandomInteger[4] + 1}], {i, 1, 9}, {j, 1, 9}]
Then this function should do the trick:
Position[ArrayReshape[Length /@ Flatten[matrix, 1], {9, 9}], 1]
Cheers,
Marco
PS: You might also like
http://mathworld.wolfram.com/notebooks/RecreationalMath/Sudoku.nb
and
http://demonstrations.wolfram.com/SudokuGame/
If the name of your matrix is mat, than this should do the job:
Map[Length, mat, {2}]
Both of these work fine, the second being more compact. Thanks.
After floundering around, however, I believe the easiest way to find the positions(s) of single element lists is to use pos=Position[ mat, {}]. For double element lists (and so on) use Position[mat, {,_}].
After you have found the position in the form {i,j} , you can recapture that element of matrix mat with Extract[ mat, pos].
KH
I see that my reply of a few minutes ago was formatted so it was unreadable. Here it is again.
Both of these work fine, the second being more compact. Thanks.
After floundering around, however, I believe the easiest way to find the positions(s) of single element lists is to use:
pos1=Position[ mat, { _ } ] .
For double element lists (and so on) use:
pos2=Position[ mat, { _ , _ }].
After you have found the position in the form { i, j } , you can recapture that element of matrix mat with Extract[ mat, pos1].
KH