简体   繁体   中英

I am trying to write a method that sums up adjacent cells in array and fills the position in a second array with the value obtained

I am pretty new to java and am wondering how I would take anxn array with these values and sum the surrounding values and then insert it into secondArray perhaps using a for loop? I appreciate the help.

firstArray:

1 1 0 1 0 1

1 0 1 0 1 0

1 1 0 0 1 1

1 1 0 0 1 1

0 0 0 1 1 0

secondArray:

2 3 3 2 3 1

4 6 3 3 4 4

4 5 3 4 4 4

3 3 3 4 5 4

2 2 2 2 3 3

Here's the mechanics (added one last row to the matrix as you said the matrix is NxN):

int[][] matrix = new int[][]{
        { 1, 1, 0, 1, 0, 1 },
        { 1, 0, 1, 0, 1, 0 },
        { 1, 1, 0, 0, 1, 1 },
        { 1, 1, 0, 0, 1, 1 },
        { 0, 0, 0, 1, 1, 0 },
        { 0, 0, 0, 0, 0, 0 }
};

int[][] result = new int[ matrix.length ][ matrix.length ];

for (int i = 0; i < matrix.length; i++) {
    for (int j = 0; j < matrix.length; j++) {
        result[ i ][ j ] = sumOfSurrounding( matrix, i, j );
    }
}

for (int i = 0; i < matrix.length; i++) {
    for (int j = 0; j < matrix.length; j++) {
        System.out.print( result[ i ][ j ] + " " );
    }
    System.out.println();
}

Now, you just have to implement the static int sumOfSurrounding( int[][] matrix, int i, int j ) method.

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