2012-01-22 43 views
1

我已經完成了所有的代碼,並堅持使用這個愚蠢的東西:當上一代與新的時代相同時,我無法停止打印......所以當打印模式爲與之前的模式一樣,它應該停止。創建新變量並製作嵌套循環

我需要在調用'step'之前複製電路板,然後比較新的和複製的電路板,並且只在已經改變的情況下打印 我需要創建一個新變量,就像我在board []中那樣,然後做一個嵌套循環像印刷品,並在裏面做新板[Y] [X] =板[Y] [X]

請幫助我,我不能停止打印它總是不斷打印。 請給我看你的語法

void step(int board[][WIDTH], int rows) { 
    int x, y; 
    int neighbors[HEIGHT][WIDTH]; 
    for (y = 0; y < rows; y++) 
     for (x = 0; x < WIDTH; x++) 
      neighbors[y][x] = count_neighbors(board, rows, y, x); 
    for (y = 0; y < rows; y++) 
     for (x = 0; x < WIDTH; x++) 
      if (board[y][x] == 1) { /* Currently alive */ 
       if (neighbors[y][x] < 2) 
        board[y][x] = 0; /* Death by boredom */ 
       else if (neighbors[y][x] > 3) 
        board[y][x] = 0; /* Death by overcrowding */ 
      } 
      else { /* Currently empty */ 
       if (neighbors[y][x] == 3) 
        board[y][x] = 1; 
      } 
} 
+0

也許讓'step'尋找變化的東西,然後返回一個布爾值,你可以在循環中使用它作爲條件。上布爾步驟 – sje397

回答

1

你只需要跟蹤更改。相當瑣碎不是複製和比較整個數組做,要少得多(執行/內存明智):

int step(int board[][WIDTH], int rows) { // now returns a bool 
    int x, y; 
    int neighbors[HEIGHT][WIDTH]; 
    int changed = 0; // save changes 
    for (y = 0; y < rows; y++) 
     for (x = 0; x < WIDTH; x++) 
      neighbors[y][x] = count_neighbors(board, rows, y, x); 
    for (y = 0; y < rows; y++) 
     for (x = 0; x < WIDTH; x++) 
      if (board[y][x] == 1) { /* Currently alive */ 
       if (neighbors[y][x] < 2) 
       { 
        board[y][x] = 0; /* Death by boredom */ 
        changed = 1; // change happened 
       } 
       else if (neighbors[y][x] > 3) 
       { 
        board[y][x] = 0; /* Death by overcrowding */ 
        changed = 1; // change happened 
       } 
      } 
      else { /* Currently empty */ 
       if (neighbors[y][x] == 3) 
       { 
        board[y][x] = 1; 
        changed = 1; // change happened 
       } 
      } 
    return changed; // return the status (changed yes/no?) 
} 

int main(void) { 
    int board[HEIGHT][WIDTH]; 
    init(board, HEIGHT); 
    while (1) { 
     print(board, HEIGHT, WIDTH); 
     if(step(board, HEIGHT) == 0) // no change 
      break; // leave the loop 
    } 
    return 0; 
} 

編輯: 如果願意,你可以和計數的實際變化(而不是僅僅說是/否)並返回更改次數。可能會保持幾乎相同。

+0

錯誤(INT板[] [寬度],INT行){:錯誤錯誤C2061:語法錯誤:識別符 '步驟' \t錯誤錯誤C2059:語法錯誤: '類型' \t錯誤錯誤C2059:語法錯誤:';' – Blondy21

+0

啊,我的錯。使用'int'作爲返回類型。畢竟C不知道'bool'。 – Mario

+0

@Mario,自C99以來,C肯定有'bool'(或'_Bool')。 –