标签:style blog color 使用 ar for sp div c
理论;
生命游戏(game of life)為1970年由英国数学家J. H. Conway所提出,某一细胞的邻居包括上、下、左、右、左上、左下、右上与右下相邻之细胞,游戏规则如下:
解法;
生命游戏的规则可简化為以下,并使用CASE比对即可使用程式实作:
package 经典; public class LifeGame { private boolean[][] map; private boolean[][] newMap; public LifeGame(int row,int col){ map=new boolean[row][col]; newMap=new boolean[row][col]; for(int i=0; i<row; i++) for(int j=0; j<col; j++) map[i][j]=true; } public void setCell(int x, int y) { map[x][y] = true; } public static void main(String[] args) { // TODO Auto-generated method stub LifeGame lifeGame=new LifeGame(10, 25); int n=0; while(n<1000) { lifeGame.next(); lifeGame.outputMap(); n++; } } public void next(){ for(int row=0; row<map.length; row++) { for(int col=0; col<map[row].length; col++) { switch(neighbor(row,col)) { case 0: case 1: case 4: case 5: case 6: case 7: case 8: newMap[row][col]=false; break; case 2: newMap[row][col]=map[row][col]; break; case 3: newMap[row][col]=true; break; } } } colyMap(); } private int neighbor(int row, int col) { // TODO Auto-generated method stub int count=0; for(int i=row-1; i<=row+1; i++) { for(int j=col-1; j<=col+1; j++) { if( i<0 || i>=map.length || j<0 || j>=map[i].length-1) continue; if(map[i][j]==true) count++; } } if(map[row][col]==true) count--; return count; } private void colyMap() { // TODO Auto-generated method stub for(int row=0; row<map.length; row++) { for(int col=0; col<map[row].length; col++) { map[row][col]=newMap[row][col]; } } } public void outputMap() { System.out.println("\n\nGame of life cell status"); for(int row = 0; row < map.length; row++) { System.out.print("\n "); for(int col = 0; col < map[0].length; col++) if(map[row][col] == true) System.out.print(‘#‘); else System.out.print(‘-‘); } } }
标签:style blog color 使用 ar for sp div c
原文地址:http://www.cnblogs.com/huangcongcong/p/4006890.html