Message Boards Message Boards

0
|
5899 Views
|
2 Replies
|
2 Total Likes
View groups...
Share
Share this post:

Swap-records operations on a matrix

Posted 11 years ago
I have the following problem:

A direct return account if and only if, simply swap two adjacent tiles horizontally or vertically, so that both remain on instead.
If the swap two records horizontally or vertically adjacent only one is in place, this does not count as direct exchange.
The number of direct exchange is doubled and that is the value of d (n).



the above is what I try to do in Mathematica, but there is something wrong, then show my code to try to solve this problem

 directos[tablero_List] := Module[{prb, directo, i},
   prb = Flatten[tablero] /. {0 -> 9};
   prb = PadRight[prb, 12, 15];
   directo = 0;
   For[i = 1, i < 10, i++,
    If[i != prb[[i]],
      Which[Abs[prb[[i]] - prb[[i + 1]]] == 1 && Mod[i, 3] != 0,
        directo++,
        Abs[prb[[i]] - prb[[i + 3]]] == 3, directo++];
     ];
   ];
  directo]

Here are some examples
directos[{{1, 5, 3}, {7, 2, 0}, {4, 8, 6}}]
directos[{{6, 3, 2}, {5, 4, 7}, {1, 0, 8}}]
directos[{{2, 1, 5}, {6, 0, 3}, {8, 7, 4}}]

when running my program it sometimes gives me the correct result and not others. For example, for the following matrix, the answer is bad
directos[{{1, 2, 5}, {6, 7, 8}, {0, 4, 3}}]

I have reviewed the matrix, and the correct result is 0, Since there are no swaps possible. We'll see you then
POSTED BY: Luis Ledesma
2 Replies
Posted 11 years ago
 In[1]:= sameRow[i_, j_] := Quotient[i-1, 3] == Quotient[j-1, 3];
 adjacentColumn[i_, j_] := Abs[i-j] == 1;
 sameColumn[i_, j_] := Mod[i-1, 3] == Mod[j-1, 3];
 adjacentRow[i_, j_] := Abs[i-j] == 3;
 directos[m_] := Module[{v = Flatten[m]},
    Total[Table[If[v[[v[[i]]]] == i &&
         (sameRow[i, v[[i]]] && adjacentColumn[i, v[[i]]] ||
          sameColumn[i, v[[i]]] && adjacentRow[i, v[[i]]]), 1, 0], {i, 1, 9}]]/2];
 
In[6]:= directos[{{1, 2, 3}, {4, 5, 6}, {7, 8, 9}}]
Out[6]= 0

In[7]:= directos[{{2, 1, 3}, {5, 4, 9}, {8, 7, 6}}]
Out[7]= 4

In[8]:= directos[{{2, 1, 3}, {9, 6, 5}, {8, 7, 4}}]
Out[8]= 3

In[9]:= directos[{{1, 2, 3}, {9, 5, 6}, {7, 8, 4}}]
Out[9]= 0

In[10]:= directos[{{1, 2, 6}, {7, 8, 9}, {4, 5, 3}}]
Out[10]= 2

In[11]:= directos[{{1, 2, 6}, {4, 5, 9}, {7, 8, 3}}]
Out[11]= 0

In[12]:= directos[{{4, 3, 5}, {6, 9, 8}, {7, 2, 1}}]
Out[12]= 0
Test this carefully
POSTED BY: Bill Simpson
Posted 11 years ago
thank you, Bill Simpson,for your invaluable help
POSTED BY: Luis Ledesma
Reply to this discussion
Community posts can be styled and formatted using the Markdown syntax.
Reply Preview
Attachments
Remove
or Discard

Group Abstract Group Abstract