I'm trying to do this homework for algorithms, they ask me to fill a two-dimensional array of int like this:
4 3 2 3 4
3 2 1 2 3
2 1 0 1 2
3 2 1 2 3
4 3 2 3 4
I tried this in java:
int[][] array = new int[5][5];
for (int i = 0; i < array.length; i++) {
for (int j = 0; j < array[i].length; j++) {
array[i][j] = Math.abs(i - j);
}
}
but it gives me something like this:
0 1 2 3 4
1 0 1 2 3
2 1 0 1 3
3 2 1 0 1
4 3 2 1 0
And it's not really the same thing, but it's the closest that I found. I wrote the code in java but it can be in any other language... the important is the "formula" I think. So if you can help me resolving this trouble it'll be nice, I tried to look for the code online but I didn't find anything... thank you.
In a two-dimensional space, the Manhattan distance between two points (x1, y1) and (x2, y2) would be calculated as: distance = |x2 - x1| + |y2 - y1| .
The Manhattan Distance between two points (X1, Y1) and (X2, Y2) is given by |X1 – X2| + |Y1 – Y2|.
Manhattan distance is calculated as the sum of the absolute differences between the two vectors. The Manhattan distance is related to the L1 vector norm and the sum absolute error and mean absolute error metric.
The Manhattan distance is simply the sum of the distance between rows and the distance between columns.
It looks as if you're looking for the distance to the center. So you first have to calculate this point:
int center = array.length / 2; //assuming a quadratic array
Then, calculating the distance is quite easy:
//for ...
array[i][j] = Math.abs(i - center) + Math.abs(j - center);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With