I'm working on a 1D Game of Life (based upon the rules set out here at Mathworld). Essentially, each generation is represented as a row of 0's or 1's (dead or alive) and the next generation is created based upon the binary representation of a "rule" command line argument.
たとえば、ルール 30 は 00011110 (30 のバイナリ) に変わり、これを使用して、新しいセルを生成するか、次の世代で消滅するビット パターンを決定します。
これをプログラムするには、前の行から (ルールを適用するために) 3 つのグループのビットにアクセスできる必要があります。以下はサンプル画像です (開始行は常に 0 で中央が 1 であることに注意してください):
00000100000 #seed row
11001011001 #generated from seed row
...........
11110010101 #n-th row, generated from n-1 row
行を生成するには、上の行のビットを 3 つのグループに分けて調べ、ルールを 1/0、ライブ/ダイの決定として適用する必要があります。
基本的に、3 ビット パターンとルールを一致させ、それを使用して子孫の 0 または 1 を出力する予定です。これは一般的なアルゴリズムです:
if three_bit_pattern == 'xxx' && rule[x] == 0/1 {print 0/1} else {print 1/0}
私が問題を抱えているプログラムの部分は、前の行の内容にアクセスすることです。私のすべての試みは、ガベージまたは不正確なデータをもたらします。
要するに、前の行の値に 3 ビットのグループでアクセスするにはどうすればよいでしょうか?
行は次のように作成されます。
int i, j, k;
int row = atoi(argv[1]) + 1;
int col = 2 * atoi(argv[1]) + 1;
int arr[col];
int output[col];
char rule[9]; //binary representation of rule (2^8 stores up to 255 + null term)
int2binary(atoi(argv[2]), &rule, 10);
for(i = 0; i < row; i++){
for(j = 0; j < col; j++){
if(i == 0){
if(j == col / 2) //print 1 in center of first row
arr[i] = 1;
else
arr[i] = 0;
printf("%d", arr[i]);
}
else{
//output[i] = arr[i-1];
output[i+1] = arr[i];
output[i+2] = arr[i+1];
output[i+3] = arr[i+2];
printf("%s", output);
}
}//end inner for_loop
printf("\n");
}//end outer for_loop
}
わかりましたので、これをかなり単純にして、2 つの配列 (前の列を保持するものと現在の列を保持するもの) を作成します。私が理解していないのは、なぜ出力配列を印刷するとガベージが生成されるのですか? output[i] = arr[i] は有効な式ではありませんか?