2017-09-13 1 views
-2

과제에서 우리는 하나의 방법만을 사용할 수 있습니다. 나는 그것에 대해 몰랐고 나는 두 가지를 썼다. 그래서 저는 어떻게해서 그것이 내 이웃 조건 방법의 기능을 삶의 방식으로 통합 할 수 있는지 물어보고 싶었습니다. 시도했지만, 내 int 이웃 초기화하는 방법을 몰라. 다음 코드를 살펴보십시오.Java :이 두 가지 방법을 하나의 방법으로 가져 오려면 어떻게해야합니까?

public static String[] life(String[] dish) { 
    String[] newGen = new String[dish.length]; 

    //TODO: implement this function 
    for (int line = 0; line < dish.length; line++) { // for loop going through each line 
     newGen[line] = ""; 
     for (int i = 0; i < dish[line].length(); i++) { // loops through every character in the line 
      String top = ""; // neighbours on the top 
      String middle = ""; // neighbors on the same line 
      String down = ""; // neighbors down 
      if (i == 0){ 
       if(line == 0){ 
        top = null; 
       } else { 
        top = dish[line-1].substring(i, i+2); 
       } 
       middle = dish[line].substring(i + 1, i +2); 
       if(line == dish.length -1){ 
        down = null; 
       } else { 
        down = dish[line + 1].substring(i, i + 2); 
       } 
      } else if (i == dish[line].length() - 1){ 
       if(line == 0){ 
        top = null; 
       } else { 
        top = dish[line - 1].substring(i - 1, i + 1); 
       } 
       middle = dish[line].substring(i - 1, i); 
       if(line == dish.length - 1){ 
        down = null; 
       } else { 
        down = dish [line + 1].substring(i - 1, i + 1); 
       } 
      } else { 
       if (line == 0){ 
        top = null; 
       } else { 
        top = dish[line - 1].substring(i - 1, i + 2); 
       } 
       middle = dish[line].substring(i - 1, i) + dish[line].substring(i+1, i+2); 
       if (line == dish.length - 1){ 
        down = null; 
       } else { 
        down = dish[line + 1].substring(i - 1, i + 2); 
       } 
      } 

      int neighbors = neighbourconditions(top, middle, down); 
      if (neighbors < 2 || neighbors > 3){ // neighbours < 2 or >3 neighbors -> they die 
       newGen[line] += "o"; 
      } else if (neighbors == 3){ 
       newGen[line] += "x"; // neighbours exactly 3 -> they spawn/live 
      } else { 
       newGen[line] += dish[line].charAt(i); // 2 neighbours -> stay 
      } 
     } 
    } 
    return newGen; 
} 

// helpmethod with three arguments and the conditions 
public static int neighbourconditions(String top, String middle, String down) { 
    int counter = 0; 
    if (top != null) { // if no one's on top 
     for (int x = 0; x < top.length(); ++x) { 
      if (top.charAt(x) == 'x') { 
       counter++; // count if an organism's here 
      } 
     } 
    } 
    for (int x = 0; x < middle.length(); ++x) { 
     if (middle.charAt(x) == 'x') { // two organisms, one on each side 
      counter++; // count if an organism's here 
     } 
    } 
    if (down != null) { // if no one's down 
     for (int x = 0; x < down.length(); ++x) { 
      if (down.charAt(x) == 'x') { // each neighbour down 
       counter++; // count if an organism's here 
      } 
     } 
    } 
    return counter; 
} 
+0

나도 몰라. 두 가지 방법의 반환 유형은 매우 다릅니다. 각 방법의 논리는 무엇입니까? –

+0

'getNeighbors'는'life()'에서 한 번만 호출합니다. 'getNeighbors'의 코드를 복사하고 그 단일 호출 대신 붙여 넣기 만하면 어떤 문제가 있습니까? – Eran

+0

'int neighbors = counter; ' – fantaghirocco

답변

3

이 질문에 대한 사소한 대답은 다른 방법을 몸으로 방법에서 코드를 복사하여 붙여 넣는 것입니다. IDE를 사용하는 경우 내장 된 리팩토링 도구를 사용하여 메소드를 인라인 할 수 있습니다 (예 : ctrl-alt-n, intellij).

그러나 이것은 미래 세대가 당신의 이름을 저주하게 만드는 종류의 행동입니다. 그것은 불쾌하고, 읽을 수없고, 유지할 수없는 코드를 만듭니다. 하지 마. 고스트캣 (GhostCat)이 논평에서 지적했듯이, 보다 작은을 만드는 방법을 찾고 있어야합니다.

한 걸음 뒤로 물러나 올바른 방법으로 문제에 접근하고 있는지 확인하십시오. 기존 코드에서 반복되는 패턴을 찾아 단순화 할 수 있는지 확인하십시오. 또는 때로는 처음부터 잘못된 접근 방식을 취한 것으로 간주하고 대안 접근 방식을 찾아야합니다.


는 지금까지 내가 해결할 수있는, 당신이하려는 모든 즉시 현재 위치 주변의 8 세포에서 x의 수를 계산하는 것입니다.

이 코드를 모두 작성하지 않아도됩니다. 당신은 간단하게 할 수있다 :

for(int row = 0; row < dish.length; row++){ // each row 
    for(int col = 0; col < dish[row].length(); col++){ // each char in the row 

    int neighbors = 0; 
    for (int r = Math.max(row - 1, 0); r < Math.min(row + 2, dish.length); ++r) { 
     for (int c = Math.max(col - 1, 0); c < Math.min(col + 2, dish[row].length()); ++c) { 
     // Don't count (row, col). 
     if (r == row && c == col) continue; 

     if (dish[r].charAt(c) == 'x') ++neighbors; 
     } 
    } 

    //here ends the interesting part for you 
    if(neighbors < 2 || neighbors > 3){ 
     // etc. 

더 적은 코드, 보조 방법이 필요 없다. 또한 불필요하게 문자열을 작성하지 않기 때문에 훨씬 효율적입니다.

+0

귀하의 도움에 감사드립니다 :). 나는 for 루프에서 대괄호와 if [statement]에 if (lines [r] .charAt (c).)를 써서 접시 [row] .length()를 작성해야한다고 생각한다. 우리가 "라인"을 정의하지 않았기 때문에 거기에. – JavaJoker204

+0

그들은 타이핑되었습니다. Fixed. –

+0

고마워,하지만 난 여전히 작은 문제가있다. "여기서 흥미로운 부분이 끝났어."거기에 newGen이있다. [row] + = dish [row] .charAt (i). 그러나 우리는 무엇을 할 수 있습니까? – JavaJoker204

4

두 번째 기능에서 수행하는 모든 작업은 첫 번째 기능에서 수행해야합니다. 그러니 기능 1로 기능 2에서 코드를 복사 :

public static String[] life(String[] dish){ 
String[] newGen= new String[dish.length]; 

//TODO: implement this functions 
for(int row = 0; row < dish.length; row++){ // each row 
    newGen[row]= ""; 
    for(int i = 0; i < dish[row].length(); i++){ // each char in the row 
     String above = ""; // neighbors above 
     String same = ""; // neighbors in the same row 
     String below = ""; // neighbors below 
     if(i == 0){ // all the way on the left 
      // no one above if on the top row 
      // otherwise grab the neighbors from above 
      above = (row == 0) ? null : dish[row - 1].substring(i, i + 2); 
      same = dish[row].substring(i + 1, i + 2); 
      // no one below if on the bottom row 
      // otherwise grab the neighbors from below 
      below = (row == dish.length - 1) ? null : dish[row + 1].substring(i, i + 2); 
     }else if(i == dish[row].length() - 1){//right 
      // no one above if on the top row 
      // otherwise grab the neighbors from above 
      above = (row == 0) ? null : dish[row - 1].substring(i - 1, i + 1); 
      same = dish[row].substring(i - 1, i); 
      // no one below if on the bottom row 
      // otherwise grab the neighbors from below 
      below = (row == dish.length - 1) ? null : dish[row + 1].substring(i - 1, i + 1); 
     }else{ // anywhere else 
      // no one above if on the top row 
      //otherwise grab the neighbors from above 
      above = (row == 0) ? null : dish[row - 1].substring(i - 1, i + 2); 
      same = dish[row].substring(i - 1, i) + dish[row].substring(i + 1, i + 2); 
      //no one below if on the bottom row 
      //otherwise grab the neighbors from below 
      below = (row == dish.length - 1) ? null : dish[row + 1].substring(i - 1, i + 2); 
     } 

     // here is the interesting part for you: 
     int neighbors = 0; 
     if(above != null){//no one above 
      for(char x: above.toCharArray()){ //each neighbor from above 
      if(x == 'x') neighbors++; //count it if someone is here 
      } 
     } 
     for(char x: same.toCharArray()){ //two on either side 
      if(x == 'x') neighbors++;//count it if someone is here 
     } 
     if(below != null){ //no one below 
      for(char x: below.toCharArray()){//each neighbor below 
      if(x == 'x') neighbors++;//count it if someone is here 
      } 
     }; 
     //here ends the interesting part for you 
     if(neighbors < 2 || neighbors > 3){ 
      newGen[row]+= "o"; // If the amount of neighbors is < 2 or >3 neighbors -> they die 
     }else if(neighbors == 3){ 
      newGen[row]+= "x"; // If the amount of neighbors is exactly 3 neighbors -> they spawn/live 
     }else{ 
      newGen[row]+= dish[row].charAt(i); // 2 neighbors -> stay 
     } 
    } 
} 

return newGen; 

}

+3

당신은 초보자입니다. 따라서 질문에 답하는 작업에 대한 보상을 제공 할 수 있습니다. 필자는 * 실제 * 대답은 읽을 수없는 코드를 읽을 수 없도록 만드는 것과 정반대의 작업이라고 생각합니다 (코드를 더 이상 분할하지 않고 메서드를 병합하는 방법). – GhostCat

관련 문제