简体   繁体   中英

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.

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);

This will also work.

int p=N-1;
for(i=0,l=N-1;i<=l;i++,l--)
{
    for(j=0,k=N-1;j<=k;j++,k--)
    {
        arr[i][j]=p;
        arr[i][k]=p;
        arr[l][j]=p;
        arr[l][k]=p;
        p--;
    }
    p=N-i-2;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM