fork(1) download
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <memory.h>
  4.  
  5. #define FieldSize 20
  6. /*#define TimeMax 200*/
  7.  
  8. /*フィールドの初期化 (ファイルの読み込み)*/
  9. void init_field(int field[FieldSize][FieldSize], char *fname){
  10. int i,j;
  11. FILE *fp;
  12.  
  13. if ((fp=fopen(fname,"r"))==NULL){
  14. printf("init_field(): Cannot open \"%s\"\n", fname);
  15. exit(1);
  16. }
  17.  
  18. for (i=0; i<FieldSize; i++) {
  19. for(j=0; j<FieldSize; j++) {
  20. fscanf(fp, "%d ", &field[i][j]);
  21. }
  22. fscanf(fp, "\n");
  23. }
  24. fclose(fp);
  25. }
  26.  
  27. int around_count(int I, int J, int field[FieldSize][FieldSize]){
  28. int i,j;
  29. int sum = 0;
  30. for(i=-1; i<=1; i++){
  31. for(j=-1 ;j<=1; j++){
  32. if (I+i < 0) continue;
  33. if (J+j < 0) continue;
  34. if (I+i >= FieldSize) continue;
  35. if (J+j >= FieldSize) continue;
  36. if (i==0 && j==0) continue;
  37. if (field[I+i][J+j]==1)
  38. sum++;
  39. }
  40. }
  41. return sum;
  42. }
  43.  
  44. void update_field(int field[FieldSize][FieldSize]){
  45. int i,j;
  46. int around;
  47. int new_field[FieldSize][FieldSize];
  48. for(i=0; i<FieldSize; i++){
  49. for(j=0; j<FieldSize; j++){
  50. new_field[i][j] = 1;
  51. around = around_count(i,j,field);
  52. if (field[i][j]==0 && around==3) continue;
  53. if (field[i][j]==1 && (around==3 || around==2)) continue;
  54. new_field[i][j] = 0;
  55. }
  56. }
  57. memcpy((void*)field, (void*)new_field, sizeof(new_field));
  58. }
  59.  
  60. void display(int field[FieldSize][FieldSize]){
  61. int i,j;
  62. for (i=0; i<FieldSize; i++) {
  63. for (j=0; j<FieldSize; j++) {
  64. if (field[i][j]==1) {
  65. printf("@ ");
  66. } else {
  67. printf("_ ");
  68. }
  69. }
  70. printf("\n");
  71. }
  72. }
  73.  
  74. int main(int argc, char *argv[]){
  75. int t;
  76. int field[FieldSize][FieldSize];
  77.  
  78. if(argc!=2){
  79. printf("実行方法 : ./a.out 初期状態のファイル\n");
  80. exit(1);
  81. }
  82.  
  83. init_field(field, argv[1]);
  84. system("clear");
  85. for (;;) {
  86. system("clear");
  87. update_field(field);
  88. display(field);
  89. /*usleep(200000);*/
  90. getchar();
  91. }
  92.  
  93. return 0;
  94. }
  95.  
Runtime error #stdin #stdout 0.01s 2724KB
stdin
Standard input is empty
stdout
実行方法 : ./a.out 初期状態のファイル