繁体   English   中英

如何在二维数组中添加相邻像元?

[英]How do you add adjacent cells in a 2d array?

我需要让firstArray中的每个单元格成为所有相邻单元格的总和,然后将该答案转储到secondArray中。 例:

具有随机数的初始数组:

3   5   11  
5   9   14   
1   2   8 

计算数组:

19  42  41  
20  49  48  
33  62  44 

3点([0] [0])是5 + 9 + 5 = 19 ,依此类推。 这是我所拥有的:

public class ProcessArray {

    private int rows;
    private int columns;
    private int [][] firstArray;
    private int [][] secondArray;


public ProcessArray(int rows, int columns) {

    this.rows=rows;
    this.columns=columns;
    firstArray = new int[rows][columns];
    secondArray = new int[rows][columns];

    initializeArray(firstArray, secondArray);

    randomlyFillArray(firstArray);
    System.out.println("Initial array with random numbers: ");
    printArray(firstArray, secondArray, rows, columns);
    getFirstArray(firstArray);
    System.out.println("Computed array:");
    computeArrayValues(firstArray);



}

private void initializeArray(int firstArray[][], int secondArray[][]){
    for(int i = 0; i <firstArray.length; i++){
        for (int j =0; j<firstArray[i].length; j++){
            firstArray[i][j] = (0);
        }

    }
    for(int i = 0; i <secondArray.length; i++){
        for (int j =0; j<secondArray[i].length; j++){
            secondArray[i][j] = (0);
        }

    }
}

public void randomlyFillArray(int firstArray[][]){
    for(int i = 0; i <firstArray.length; i++){
        for (int j =0; j<firstArray[i].length; j++){
            firstArray[i][j] = (int)(Math.random()*15);
        }

    }

}

//here's where I try to have it add, I don't know what loop to have it run to go to each spot in the `firstArray`:

public void computeArrayValues(int firstArray[][]){
    int x=1;
    int y=1;
    int sum;

    int topLeft = firstArray[x-1][y-1];
    int top = firstArray[x][y-1];
    int topRight = firstArray[x+1][y-1];
    int midLeft = firstArray[x-1][y];
    int midRight = firstArray[x+1][y];
    int botLeft = firstArray[x-1][y+1];
    int bot = firstArray[x][y+1];
    int botRight = firstArray[x+1][y+1];

    secondArray[0][0]= (bot+botRight+midRight);

    for (x=0; x<firstArray.length; x++){
        for(y=0; y<firstArray.length; y++){
    secondArray[x][y] = (topLeft+top+topRight+midLeft+midRight+botLeft+bot+botRight);
        }
    }
    System.out.println(secondArray[x][y]);
}

public void printArray(int firstArray[][], int secondArray[][], int rows, int columns){

    for (int i = 0; i < rows; i++){
        for (int j = 0; j < columns; j++){
            System.out.printf(String.format("%4s", firstArray[i][j]));
        }
        System.out.println();
    }

}

public int[][] getFirstArray(int array[][]){
    array = firstArray;
    return array;

}

public int[][] getSecondArray(int array[][]){
    array = secondArray;
    return array;

}

}

假设您正在寻找有关替代方法的建议,我建议封装单元格坐标并使用单元格流而不是迭代。 假定使用Java 8(自然):

class Cell {
    private final int row;
    private final int col;

    private Cell(int row, int col) {
        this.row = row;
        this.col = col;
    }

    public static Stream<Cell> streamCells(int rows, int cols) {
        return IntStream.range(0, rows)
            .flatMap(row -> IntStream.range(0, cols)
                .flatMap(col -> new Cell(row, col)));
    }

    public Stream<Cell> streamAdjacentCells(int rows, int cols) {
        return IntStream.range(row - 1, row + 1)
            .flatMap(row -> IntStream.range(col - 1, col + 1)
                .flatMap(col -> new Cell(row, col)))
            .filter(cell -> cell.row >= 0 && cell.col >= 0)
            .filter(cell -> cell.row < rows && cell.col < cols)
            .filter(cell -> cell.row != this.row && cell.col != this.col);
    }

    public int getValue(int[][] array) {
        return array[row][col];
    }

    public void setValue(int[][] array, int value) {
        array[row][col] = value;
    }
}

然后,设置相邻值的代码非常简单:

int[][] destination = new int[rows][cols];
Cell.streamCells(rows, cols)
    .forEach(cell -> setValue(
        destination,
        cell.streamAdjacentCells(rows, cols)
            .mapToInt(adj -> getValue(source, adj))
            .sum()));

这将满足规定的要求,但是运行带有示例数据的程序将输出:

19 42 28 
20 49 35 
16 37 25 

对于所有相邻单元格的总和,这将是正确的输出(如果我误解了这个问题,请告诉我)。

public class ArraySum {
    static int[][] sum(int array[][]) {
        // Asuming square arrays
        int size = array.length;

        int result[][] = new int[size][size];

        // For every cell in the table
        for (int i = 0; i < size; i++) {
            for (int j = 0; j < size; j++) {

                // Iterate the neighbors
                for (int n = -1; n <= 1; n++) {
                    for (int m = -1; m <= 1; m++) {
                        // Discard the cell     
                        if (n == 0 && m == 0) {
                            continue; 
                        }
                        int ii = i - n;
                        int jj = j - m;
                        // Check if the neighbor coordinates are 
                        // inside of the array bounds 
                        if (ii >= 0 && ii < size && jj >= 0 && jj < size) {
                            result[i][j] += array[ii][jj];
                        }
                    }
                }
            }
        }   
        return result;
    }   


    public static void main(String... args) {
        int a[][] = { {3, 5, 11}, 
                      {5, 9, 14}, 
                      {1, 2,  8} };
        int r[][] = sum(a);

        for (int i = 0; i < 3; i++) {
            for (int j = 0; j < 3; j++) { 
                System.out.printf("%d ", r[i][j]);
            }
            System.out.println();
        }
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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