Hello friends I'm working on a mini project (8-puzzle) for which I need the distance manhattan and have programmed it in the following way
valabs[a_, b_] := If [a > b, a - b, b - a]
manhattan[tablero_List] := Module[{i, j, x, y, cuenta = 0},
For[i = 1, i <= 3, i++,
For[j = 1, j <= 3, j++,
If[tablero[[i, j]] == 0
,
cuenta += 0;
,
x = Quotient[tablero[[i, j]] - 1, 3] + 1;
y = Mod[tablero[[i, j]] - 1, 3] + 1;
cuenta = cuenta + valabs[x, i] + valabs[y, j];
];
];
];
cuenta
]
Remember that you should not count zero, wanting to do the same with function ManhattanDistance get a different value, here is an example. With my function
In[1]:= manhattan[{{2, 1, 5}, {6, 3, 4}, {8, 0, 7}}]
Out[1]= 13
Now with ManhattanDistance
In[2]:= ManhattanDistance[{{2, 1, 5}, {6, 3, 4}, {8, 0, 7}}, {{1, 2, 3}, {4, 5, 6}, {7, 8, 0}}]
Out[2]= 11
Someone could say why am I having such a result, I think that there is some trick to be able to do the same, it would be of much help some guidance, because I plan to keep using ManhattanDistance later in my code, greetings to all.