2015-01-28 5 views
1

firstArray의 각 셀에 모든 인접 셀의 합계가 있어야하고 그 응답을 secondArray로 덤프해야합니다. 예 : 난수인접 셀을 2D 배열에 어떻게 추가합니까?

초기 배열 :

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; 

} 

}

+0

무엇이 당신 질문입니까? 코드 또는 대체 접근법에 대한 의견을 묻고 있습니까? – sprinter

+1

예제 초기 배열 및 계산 된 배열이 맞습니까? 귀하의 설명에서 계산 된 배열의 왼쪽 하단 셀은 5 + 9 + 2 = 16이어야합니다. 그러나 당신은 그 33을 말했습니다. 당신의 질문을 정확하게 이해하지 못했습니까? –

답변

0

당신이 다른 방법에 대한 제안을 찾고 가정하면, 내가 셀 좌표를 캡슐화 대신 반복의 세포의 스트림을 사용하는 것이 좋습니다 것입니다. 그런 다음

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

이이 명시된 요구 사항을 충족하지만, 예를 들어, 데이터를 출력으로 프로그램을 실행이 (자연스럽게) 자바 (8) 가정 :

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(); 
     } 
    } 
} 
관련 문제