Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Filling a 2d array with manhattan distance pattern

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.

like image 379
Cris Avatar asked Jul 31 '15 09:07

Cris


People also ask

How do you calculate Manhattan distance in 2d array?

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| .

How do you code a Manhattan distance?

The Manhattan Distance between two points (X1, Y1) and (X2, Y2) is given by |X1 – X2| + |Y1 – Y2|.

How do you use Manhattan distance?

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.

How do you find the distance between two matrices in Manhattan?

The Manhattan distance is simply the sum of the distance between rows and the distance between columns.


1 Answers

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);
like image 137
Nico Schertler Avatar answered Sep 29 '22 01:09

Nico Schertler