2017-10-13 11 views
1

2 차원 배열을 사용하여 Conway의 삶의 게임을하려고합니다. 이 방법은 2 차원 배열의 모든 위치를보고 그 이웃을 확인하고 위치를 둘러싸고있는 이웃 수를 계산합니다 (0은 비어 있고 1은 점유 됨). 그런 다음 일부 논리를 수행하고 그 위치가 죽었는지 또는 살아 있는지 결정합니다. 내가 겪고있는 문제는 tempMatrix의 값이 잘못된 두 번째 위치를 확인할 때까지 있다는 것입니다. 저는 처음에 첫 번째 위치 [0] [0]을 확인했으며 0에서 1로 변경되었으며 이유는 알지 못합니다. 당신의 도움에 미리 감사드립니다!2 차원 배열 읽기 관련 문제 - Java

public static int[][] Evolve(int[][] _array){ 
    inputMatrix = _array; 
    outputMatrix = inputMatrix; 
    int [][] tempMatrix = inputMatrix; 
    System.out.println("Output Matrix:"); 
    for (int x = 0; x < size; x++){ 
     for (int y = 0; y < size; y++){ 
      int neighbor_count = 0; 
      ArrayList<int[]> neighbors = getNeighbors(x,y); 
      for(int[] neighbor: neighbors){ 
       int tempX = neighbor[0]; 
       int tempY = neighbor[1]; 
       int temp = tempMatrix[tempX][tempY]; 
       if(temp == 1){ 
        neighbor_count++; 
       } 
      } 
      if(tempMatrix[x][y] == 1){ 
       if(neighbor_count == 1 || neighbor_count > 3) { 
        outputMatrix[x][y] = 0; 
       } 
       else{ 
        outputMatrix[x][y] = 1; 
       } 
      }else if(neighbor_count == 3){ 
       outputMatrix[x][y] = 1; 
      }else{ 
       outputMatrix[x][y] = 0; 
      } 
      System.out.printf("%2d ",outputMatrix[x][y]); 
     } 
     System.out.println(); 
    } 
    return outputMatrix; 
} 
+2

'outputMatrix'와'tempMatrix'는 단순히'inputMatrix'를 가리키며 모두 똑같습니다. 현재 배열은 1 개이지만 배열에 액세스하는 데 사용할 수있는 변수 이름은 3 개입니다. 귀하의 의도는 실제로 복사본을 만드는 것이었지만 자동으로 발생하지는 않습니다. –

+0

참고 사항 : [배열 자바 복사본 만들기] (https://stackoverflow.com/questions/5785745/make-copy-of-array-java) –

+0

배열의 값이 0과 1 인 경우 왜 'boolean [] []'대신에? – jsheeran

답변

0

귀하의 inputMatrixoutputMatrixtempMatrix 같은 2 차원 배열을 참조한다. 다음 코드

if(tempMatrix[x][y] == 1){ 
      if(neighbor_count == 1 || neighbor_count > 3) { 
       outputMatrix[x][y] = 0; 
      } 
      else{ 
       outputMatrix[x][y] = 1; 
      } 
     }else if(neighbor_count == 3){ 
      outputMatrix[x][y] = 1; 
     }else{ 
      outputMatrix[x][y] = 0; 
     } 

하여 tempMatrix의 값을 outputMatrix을 수정할 때 따라서,도 변경됩니다. 따라서 모든 세 행렬에 대해 새로운 2D 배열을 만든 다음 값을 복사 해보십시오.

int inputMatrix[][]=new int[dimension][dimension]; 

이제 inputMatrix_array 행렬의 값을 복사한다.

+0

이제 두 개의 새 배열을 만들고 _array의 값을 각 배열에 복사합니다. 필요하지 않았기 때문에 입력 행렬을 없애 버렸지 만 여전히 같은 문제가 발생합니다. – DiscoJesus127