challenge ライフゲーム

セルオートマトンに関するお題です. 
2次元タイプの'ライフゲーム'を実装して下さい. 
初期値としては10行10列程度の格子上の平面に0.3程度の人口(?)密度を考え, 
末端はループするようにして下さい. (例: 座標[-1, -1] = [10, 10])

それだけだと簡単すぎると思われる方は, 
過密状態で間引きが発生するような機能を組み込んで下さい. 
間引きは, 少なくともその後の1時間ステップにおける死亡率が, 
それをしなかった場合よりも小さくなれば結構です. 
(死亡率の最小化は複雑性が高すぎる感がありますし. )
サンプル:
t = 0
[ ][*][ ][ ][ ][ ][*][*][*][ ]
[ ][ ][ ][ ][*][ ][ ][*][*][ ]
[ ][ ][ ][*][ ][ ][*][ ][*][ ]
[*][ ][*][*][ ][ ][*][ ][ ][ ]
[ ][*][ ][ ][ ][ ][ ][ ][*][ ]
[*][ ][ ][ ][*][ ][*][*][ ][*]
[ ][*][ ][ ][ ][ ][*][ ][ ][ ]
[ ][ ][ ][ ][ ][ ][ ][ ][ ][*]
[*][ ][ ][ ][ ][ ][*][ ][ ][*]
[ ][ ][ ][ ][*][*][ ][ ][*][ ]
t = 1
[ ][ ][ ][ ][*][ ][ ][ ][ ][*]
[ ][ ][ ][ ][ ][*][ ][ ][ ][*]
[ ][ ][*][ ][*][*][*][ ][*][*]
[ ][*][ ][*][ ][ ][ ][ ][ ][*]
[ ][ ][*][*][ ][*][*][ ][*][ ]
[ ][*][ ][ ][ ][*][*][ ][*][*]
[ ][ ][ ][ ][ ][*][*][*][*][*]
[ ][ ][ ][ ][ ][ ][ ][ ][ ][*]
[*][ ][ ][ ][ ][*][ ][ ][*][ ]
[*][ ][ ][ ][ ][ ][ ][ ][ ][ ]

Posted feedbacks - C#

C#で書いてみました。特に「間引き」の処理は入れていません。

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
using System;

public class LifeGame {
    private int time_ = 0;
    private readonly bool[][] matrix_;

    public LifeGame(int rows, int cols) {
        Random random = new Random();
        matrix_ = new bool[rows][];
        for (int rowIndex = 0; rowIndex < rows; rowIndex++) {
            matrix_[rowIndex] = new bool[cols];
            for (int index = 0; index < cols; index++) {
                if (random.NextDouble() < 0.3) {
                    matrix_[rowIndex][index] = true;
                }
            }
        }
    }

    public int Time {
        get {
            return time_;
        }
    }
    public String GetDisplayMatrix() {
        System.Text.StringBuilder builder = new System.Text.StringBuilder();
        foreach (bool[] row in matrix_) {
            foreach (bool cell in row) {
                builder.AppendFormat("[{0}]", cell? "*": " ");
            }
            builder.Append('\n');
        }
        return builder.ToString();
    }


    public void NextStep() {
        bool[][] oldMatrix = CopyMatrix(matrix_);
        for (int rowIndex = 0; rowIndex < matrix_.Length; rowIndex++) {
            for (int colIndex = 0; colIndex < matrix_[rowIndex].Length; colIndex++) {
                matrix_[rowIndex][colIndex] = Next(rowIndex, colIndex, oldMatrix);
            }
        }
        time_++;
    }
    private bool[][] CopyMatrix(bool[][] matrix) {
        bool[][] result = new bool[matrix.Length][];
        for (int index = 0; index < matrix.Length; index++) {
            result[index] = new bool[matrix[index].Length];
            matrix[index].CopyTo(result[index], 0);
        }
        return result;
    }
    private bool Next(int row, int col, bool[][] matrix) {
        bool now = matrix[row][col];
        int count = GetCell(matrix, row - 1, col - 1)
                + GetCell(matrix, row - 1, col)
                + GetCell(matrix, row - 1, col + 1)
                + GetCell(matrix, row, col - 1)
                + GetCell(matrix, row, col + 1)
                + GetCell(matrix, row + 1, col - 1)
                + GetCell(matrix, row + 1, col)
                + GetCell(matrix, row + 1, col + 1);
        if (now) {
            return (count == 2 || count == 3);
        } else {
            return (count == 3);
        }
    }
    private int GetCell(bool[][] matrix, int rowIndex, int colIndex) {
        int y = rowIndex;
        while (y < 0) y += matrix.Length;
        while (y >= matrix.Length) y -= matrix.Length;

        bool[] row = matrix[y];
        int x = colIndex;
        while (x < 0) x += row.Length;
        while (x >= row.Length) x -= row.Length;

        return row[x]? 1: 0;
    }


    [STAThread]
    static void Main(string[] args) {
        LifeGame game = new LifeGame(10, 10);

        Console.WriteLine("t={0}", game.Time);
        Console.WriteLine(game.GetDisplayMatrix());
        game.NextStep();
        Console.WriteLine("t={0}", game.Time);
        Console.WriteLine(game.GetDisplayMatrix());

        Console.ReadLine();
    }
}

こんなんでどうでしょう?
位置ごとに生死の情報を持たせるのではなく、
各セルに注目して、各セルに位置と生死の情報を持たせたらどんなコードになるかな?と思い書いてみました。
でも、周囲のセルをカウントするときに位置からセルの生死を判断してるので中途半端ですね。
間引きは題意がよくわからなかったので実装せず。
  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
//http://ja.doukaku.org/126/ 投稿用

//Wikipediaライフゲーム
//http://ja.wikipedia.org/wiki/%E3%83%A9%E3%82%A4%E3%83%95%E3%82%B2%E3%83%BC%E3%83%A0

using System;
using System.Collections.Generic;
class LifeGame {
    const int SIZE = 10;//変更したらCellクラスのSIZEも要変更
    static void Main(string[] args) {
        string start =
@"
□■□□□□■□□□
■□□□□■□□□□
■■■□□■■■□□
□□□□□□□□□□
□□□□□□□□□□
□□□□□□□□□□
□□□□□□□□□□
□□□□□□□□□□
□□□□□□□□□□
□□□□□□□□□□";//SIZE * SIZEの文字列
        start = start.TrimStart(new char[] { '\n', '\r' });//最初の改行を取り除く
        char[][] field = new char[SIZE][];//ライフゲームテーブル
        List<Cell> cells = new List<Cell>();//セル

        //startをfieldにセットする
        for(int y = 0; y < SIZE; y++) {//行でループ
            field[y] = start.Split(new char[] { '\n' })[y].ToCharArray();//改行で分割して文字配列にしてセット
        }

        //fieldからCellを生成
        for(int y = 0; y < SIZE; y++) {//field縦ループ
            for(int x = 0; x < SIZE; x++) {//field横ループ
                cells.Add(new Cell(field, x, y, field[y][x] == '■'));//Cellに座標をセットしてcellsに追加
            }
        }

        //メインループ
        while(true) {
            //出力
            Console.Clear();
            foreach(char[] str in field) {
                Console.WriteLine(str);
            }

            System.Threading.Thread.Sleep(300);//ウェイト            

            //次回の生死を判定、セット
            foreach(Cell cell in cells) {
                cell.SetNextLife();
            }

            //判定した生死をfieldに反映
            foreach(Cell cell in cells) {
                cell.SetField();
            }
        }
    }
}

//各セルのデータ
class Cell {
    const int SIZE = 10;//変更したらLifeGameクラスのSIZEも要変更
    char[][] Field;

    //位置
    int X;
    int Y;

    bool Life;//状態
    bool NextLife;//次回の状態(一時保存用)

    public Cell(char[][] field, int x, int y, bool life) {
        Field = field;
        X = x;
        Y = y;
        Life = life;
    }

    //次回の生死を判定
    public void SetNextLife() {
        switch(GetCount()) {
        case 3://誕生、維持
            NextLife = true;
            break;
        case 2://維持
            NextLife = Life;
            break;
        default://死亡
            NextLife = false;
            break;
        }
    }

    //判定した生死をfieldに反映
    public void SetField() {
        Field[Y][X] = NextLife ? '■' : '□';
        Life = NextLife;
    }

    //セル周囲の生きているセルをカウント
    private int GetCount() {
        int count = 0;
        for(int y_ = -1; y_ <= 1; y_++) {
            for(int x_ = -1; x_ <= 1; x_++) {
                if(!(x_ == 0 && y_ == 0)) {
                    int locationX = GetRoopLocation(X, x_);
                    int locationY = GetRoopLocation(Y, y_);
                    if(Field[locationY][locationX] == '■') count++;
                }
            }
        }
        return count;
    }

    //fieldの端と端を繋ぐ
    private int GetRoopLocation(int location, int direction) {
        switch(location + direction) {
        case -1:
            return SIZE - 1;
        case SIZE:
            return 0;
        default:
            return location + direction;
        }
    }
}

がっつりと勘違いしてました。
こっそりと修正。
  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
//http://ja.doukaku.org/126/ 投稿用

//Wikipediaライフゲーム
//http://ja.wikipedia.org/wiki/%E3%83%A9%E3%82%A4%E3%83%95%E3%82%B2%E3%83%BC%E3%83%A0

using System;
using System.Collections.Generic;
class LifeGame {
    const int SIZE = 10;//変更したらCellクラスのSIZEも要変更
    static void Main(string[] args) {
        string start =
@"
□■□□□□■□□□
■□□□□■□□□□
■■■□□■■■□□
□□□□□□□□□□
□□□□□□□□□□
□□□□□□□□□□
□□□□□□□□□□
□□□□□□□□□□
□□□□□□□□□□
□□□□□□□□□□";//SIZE * SIZEの文字列
        start = start.TrimStart(new char[] { '\n', '\r' });//最初の改行を取り除く
        char[][] field = new char[SIZE][];//ライフゲームテーブル
        List<Cell> cells = new List<Cell>();//セル

        //startをfieldにセットする
        //for(int y = 0; y < SIZE; y++) {//行でループ
        //    field[y] = start.Split(new char[] { '\n' })[y].ToCharArray();//改行で分割して文字配列にしてセット
        //}

        //ランダムにfieldを生成
        Random rnd = new Random();
        for(int j = 0 ;j<SIZE;j++) {
            field[j] = new char[SIZE];
            for(int i = 0; i < SIZE;i++ ) {
                field[j][i] = rnd.Next(0, 100) <= 30 ? '■' : '□';
            }
        }

        //fieldからCellを生成
        for(int y = 0; y < SIZE; y++) {//field縦ループ
            for(int x = 0; x < SIZE; x++) {//field横ループ
                cells.Add(new Cell(field, x, y, field[y][x] == '■'));//Cellに座標をセットしてcellsに追加
            }
        }

        //メインループ
        while(true) {
            //出力
            Console.Clear();
            foreach(char[] str in field) {
                Console.WriteLine(str);
            }

            System.Threading.Thread.Sleep(300);//ウェイト            

            //次回の生死を判定、セット
            foreach(Cell cell in cells) {
                cell.SetNextLife();
            }

            //判定した生死をfieldに反映
            foreach(Cell cell in cells) {
                cell.SetField();
            }
        }
    }
}

//各セルのデータ
class Cell {
    const int SIZE = 10;//変更したらLifeGameクラスのSIZEも要変更
    char[][] Field;

    //位置
    int X;
    int Y;

    bool Life;//状態
    bool NextLife;//次回の状態(一時保存用)

    public Cell(char[][] field, int x, int y, bool life) {
        Field = field;
        X = x;
        Y = y;
        Life = life;
    }

    //次回の生死を判定
    public void SetNextLife() {
        switch(GetCount()) {
        case 3://誕生、維持
            NextLife = true;
            break;
        case 2://維持
            NextLife = Life;
            break;
        default://死亡
            NextLife = false;
            break;
        }
    }

    //判定した生死をfieldに反映
    public void SetField() {
        Field[Y][X] = NextLife ? '■' : '□';
        Life = NextLife;
    }

    //セル周囲の生きているセルをカウント
    private int GetCount() {
        int count = 0;
        for(int y_ = -1; y_ <= 1; y_++) {
            for(int x_ = -1; x_ <= 1; x_++) {
                if(!(x_ == 0 && y_ == 0)) {
                    int locationX = GetRoopLocation(X, x_);
                    int locationY = GetRoopLocation(Y, y_);
                    if(Field[locationY][locationX] == '■') count++;
                }
            }
        }
        return count;
    }

    //fieldの端と端を繋ぐ
    private int GetRoopLocation(int location, int direction) {
        switch(location + direction) {
        case -1:
            return SIZE - 1;
        case SIZE:
            return 0;
        default:
            return location + direction;
        }
    }
}

初投稿です 間引きに関しては・・・これでいいのかよくわかりません。

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
using System;
using System.Collections.Generic;

class Program
{
    static void Main(string[] args)
    {
        LifeGame lg = new LifeGame(10, 10, 0.3, true);
        short i = 1;
        while (i != 0)
        {
            Console.Clear();
            Console.WriteLine("t = {0}", i++);
            lg.outputConsole();
            lg.scanField();

            System.Threading.Thread.Sleep(100);
        }
    }
}

class LifeGame
{
    public const int DEAD = 0;
    public const int ALIVE = 1;
    //横の長さ
    private int width_;
    public int Width{get{return width_;}}
    //縦の長さ
    private int height_;
    public int Height{get{return height_;}}
    //フィールド
    private int[,] field;
    //間引きのON(true)、OFF(false)
    private bool skipPixelFlag;

    public LifeGame(int w, int h, double rate, bool flag)
    {
        width_ = w;
        height_ = h;
        skipPixelFlag = flag;
        field = new int[w, h];
        createField(rate);
        //デバッグ用
        //width_ = 10;
        //height_ = 10;
        //field = new int[10, 10]
        //{
        //    {0,1,0,0,0,0,0,0,0,0},
        //    {0,0,1,0,0,0,0,0,0,0},
        //    {1,1,1,0,0,0,0,0,0,0},
        //    {0,0,0,0,0,0,0,0,0,0},
        //    {0,0,0,0,0,0,0,0,0,0},
        //    {0,0,0,0,0,0,0,0,0,0},
        //    {0,0,0,0,0,0,0,0,0,0},
        //    {0,0,0,0,0,0,0,0,0,0},
        //    {0,0,0,0,0,0,0,0,0,0},
        //    {0,0,0,0,0,0,0,0,0,0}
        //};
    }

    //ランダム生成
    private void createField(double rate)
    {
        int count = (int) (Width * Height * rate);
        Random random = new Random();
        do
        {
            int w = random.Next(Width), h = random.Next(Height);
            if (field[w, h] == DEAD) field[w, h] = ALIVE; else continue;
            count--;
        } while (count > 0);
    }

    //次の世代作成
    public void scanField()
    {
        int[,] temp = new int[Width, Height];
        for (int i = 0; i < Width; i++)
            for (int j = 0; j < Height; j++)
            {
                int value = aroundField(i, j);

                if (value == 3) temp[i, j] = ALIVE;
                else if (value == 2) temp[i, j] = field[i, j];
                else temp[i, j] = DEAD;
            }

        field = (int[,]) (temp.Clone());
        if (skipPixelFlag) skipPixelField();//間引き
    }

    //間引き
    //といっても、これでいいのか不明。
    //周りに4個以上ALIVEがあったらその枡をDEADにする
    private void skipPixelField()
    {
        for (int i = 0; i < Width; i++)
            for (int j = 0; j < Height; j++)
            {
                int value = aroundField(i, j);
                if (value > 4) field[i, j] = DEAD;
            }

    }

    //周りの生きてる枡の数
    private int aroundField(int w, int h)
    {
        int sum = 0;
        for (int i = w - 1; i <= w + 1; i++)
            for (int j = h - 1; j <= h + 1; j++)
                if (i != w || j != h)
                    sum += field[getIndex(i, Width), getIndex(j, Height)];
        return sum;
    }

    //ループインデックス作成
    private int getIndex(int n, int max)
    {
        return (n + max) % max;
    }

    //出力
    public void outputConsole()
    {
        for (int i = 0; i < Width; i++)
        {
            for (int j = 0; j < Height; j++)
            {
                Console.Write((field[i, j] == ALIVE) ? "■" : "□");
            }
            Console.WriteLine();
        }
        Console.WriteLine();
    }
}

初投稿です。 長いコードですが、自分はC#なら富豪的に書きます。

間引きはわかりませんでした。 実装してみましたが、うまく動いてないような気がします・・・

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
using System;
using System.Collections.Generic;
using System.Linq;
using System.Data.Linq;
using System.Drawing;
using System.Diagnostics;

public class LifeGame
{
    static void Main(string[] args)
    {
Start:
        Setting.Size = 10;      //格子サイズ
        Setting.InitRandomRate = 0.3; //人口密度
        Setting.Log = LogType.All;

        CellManager cm;

        Console.Clear();
        Console.WriteLine("seed = ?");
        int seed=0, wait = 50;
        int.TryParse(Console.ReadLine(), out seed);

        //---------------------------------------------------------------------
        cm = new CellManager(seed);
        int step = 0, step2 = 0;
        string last = string.Empty;//こうちゃくしたら止めるため
        while (true)
        {
            Console.WriteLine("seed = {0}---間引きなし:step={1}---間引きあり:step={2}", seed, step, step2);
            WriteSet(cm);
            step++;
            System.Threading.Thread.Sleep(wait);
            cm.ToNext();
            Console.Clear();
            if (cm.AliveCount == 0 || last == cm.EqualFlag)
                break;
            last = cm.EqualFlag;
        };

        Console.WriteLine("間引きあり : M/手動, M以外/自動");
        bool manual = Console.ReadKey().Key == ConsoleKey.M;
        Console.Clear();

        cm = new CellManager(seed);
        while (true)
        {
            Console.WriteLine("seed = {0}---間引きなし:step={1}---間引きあり:step={2}", seed, step, step2);
            cm.Cull_2();//間引き
            WriteSet(cm);
            step2++;
            if (manual)
                Console.ReadKey();
            else
                System.Threading.Thread.Sleep(wait);
            cm.ToNext();
            Console.Clear();
            if (cm.AliveCount == 0 || last == cm.EqualFlag)
                break;
            last = cm.EqualFlag;
        };
        Console.WriteLine("seed = {0}---間引きなし:step={1}---間引きあり:step={2}", seed, step, step2);

        //-----間引きしたときの生存数up率のn回の平均値を出してみるテスト。-------
        //int n = 100;
        //Setting.InitRandomRate = 0.3; //人口密度
        //Setting.Log = LogType.All;

        //Console.WriteLine("回数 = ?");
        //int.TryParse(Console.ReadLine(), out n);

        //var avg = Enumerable.Range(seed, n).Select(
        //    (seedValue, idx) =>
        //    {
        //        WriteState(string.Format("seed={0}", seedValue));
        //        WriteState("non cull");
        //        cm = new CellManager(seedValue);
        //        double nonCull = Test(cm);
        //        WriteState("cull");
        //        cm = new CellManager(seedValue);
        //        cm.Cull_2();
        //        double cull = Test(cm);

        //        var up = nonCull != 0 ? ((cull / nonCull) - 1.0d) * 100 : cull;
        //        WriteSimple(string.Format("間引きすると生存数は{0}% up", up));
        //        WriteState("**************************************************");
        //        if (double.IsInfinity(up))
        //            throw new InvalidOperationException();
        //        WriteNon(idx.ToString());
        //        return up;
        //    }
        //).Average();
        //WriteSimple(string.Format("平均 = {0}% up", avg));
        //---------------------------------------------------------------------

        Console.WriteLine("もう一度? y/n");
        if (Console.ReadKey().Key == ConsoleKey.Y)
            goto Start;
    }
    static int Test(CellManager cm)
    {
        WriteSet(cm);

        cm.ToNext();
        WriteState("next");
        WriteSet(cm);
        WriteState("-------------------");
        return cm.AliveCount;
    }
    static void WriteSet(CellManager cm)
    {
        WriteFigure(cm.CellLines);
        WriteState(string.Format("生存数={0} ", cm.AliveCount));
    }

    static void WriteFigure(IEnumerable<IGrouping<int,Cell>> data)
    {
        if ((Setting.Log & LogType.All) != LogType.All)
            return;
        foreach (var group in data)
        {
            var lineString = new string(group.Select(c => c.IsAlive ? '■' : '□').ToArray());
            Console.WriteLine(lineString);
        }
    }
    static void WriteNon(string text)
    {
        if (Setting.Log == LogType.Non) 
            Console.WriteLine(text);
    }
    static void WriteState(string text)
    {
        if((Setting.Log & LogType.State) == LogType.State)
            Console.WriteLine(text);
    }
    static void WriteSimple(string text)
    {
        if((Setting.Log & LogType.Simple) == LogType.Simple)
            Console.WriteLine(text);
    }
}

[Flags]
public enum LogType
{
    Non     = 0x000 ,   //表示しない(進捗のみ)
    Simple  = 0x001 ,   //最低限の数値
    State   = 0x011 ,   //詳細な数値
    All     = 0x111     //詳細な数値と図形
}
static public class Setting
{
    static public int Size { get; set; }
    static public int MatrixSize
    {
        get { return Size * Size; }
    }
    static public LogType Log { get; set; }
    static public double InitRandomRate { get; set; }
}
static public class CorrectExtension
{
    static public int CorrectValue;
    static public int Correct(this int a)
    {
        while (a < 0) a += Setting.Size;
        return a % Setting.Size;
    }
}
public class CellManager
{
    Random rand;
    List<Cell> data;

    public int AliveCount { get { return data.Count(cell => cell.IsAlive); } }
    public IEnumerable<Cell> Cells
    {
        get
        {
            return data.AsEnumerable();
        }
    }
    public IEnumerable<IGrouping<int, Cell>> CellLines
    {
        get
        {
            return Cells.GroupBy(c => Get(c).Y).OrderBy(gp => gp.Key);
        }
    }
    public string EqualFlag
    {
        get
        {
            return new string(data.Select(c => c.IsAlive ? '1' : '0').ToArray());
        }
    }

    public Cell newCell(bool alive)
    {
        return new Cell { Manager = this,IsAlive = alive };
    }

    public CellManager(int seed)
    {
        rand = new Random(seed);
        data = new List<Cell>();
        for (int i = 0; i < Setting.MatrixSize; i++)
        {
            data.Add(newCell(rand.NextDouble() < Setting.InitRandomRate));
        }
    }
    public CellManager(IEnumerable<bool> initData)
    {
        if (initData.Count() != Setting.MatrixSize)
            throw new ArgumentException();
        data = new List<Cell>(initData.Select(isAlive => newCell(isAlive )));
    }

    public void ToNext()
    {
        var nextData = data.Select(d => d.Next).ToArray();
        for (int i = 0; i < nextData.Length; i++)
        {
            data[i].IsAlive = nextData[i];
        }
    }

    // 間引き
    public void Cull_2()
    {
        //生きているやつをリストアップする。
        var aliveNoList = data.Where(cell => cell.IsAlive).Select(cell => data.IndexOf(cell)).ToArray();
        foreach (var no in aliveNoList)
        {
            //自分は次回生きてるか。
            var nextMe = data[no].Next;
            //現在の自分の回りの生存数
            var nowAround = data[no].AroundAliveCount;
            //次回の回りの生存数。
            var nowNext = data[no].Around.Count(c => c.Next);
            //死んでみる
            data[no].IsAlive = false;
            //自分が死んだ場合の次回の回りの生存数
            var testNext = data[no].Around.Count(c => c.Next);
            //回りの生存するが増えるなら死ぬ
            if (testNext > (nowNext + (nextMe ? 1 : 0)))
                continue;
            ////減らない(=同じ)で、4つ以上いたらどうせ死ぬから先に死ぬ
            // ※これやると、人口率0.3では下がりますが、人口率0.9ではこれがないと↑の間引きだけじゃうまくできない。
            //if (testNext == (nowNext + (nextMe ? 1 : 0)) && !nextMe)
            //    continue;
            data[no].IsAlive = true;
        }
    }

    // 間引き
    // 全パターンを調べてみる。遅すぎて論外でした。そもそも動くのかわかりません。
    public void Cull_1()
    {
        //生きているやつをリストアップする。
        var aliveNoList = data.Where(cell => cell.IsAlive).Select(cell => data.IndexOf(cell)).ToArray();
        int min = int.MaxValue;
        UInt64 minPattern = 0;//64個より多いとダメだけど、とりあえず気にしない。

        for (UInt64 patten = 0; patten <= UInt64.MaxValue; patten++)
        {
            //パターン対象を殺してみる
            for (int i = 0; i < aliveNoList.Count(); i++)
            {
                if ((patten&(((UInt64)1) << i)) != 0)
                {
                    data[aliveNoList[i]].IsAlive = false;
                }
            }
            //次回死んでいる数を調べ、最小ならパターン番号を覚える
            var a = data.Count(c => !c.Next);
            if (data.Count(c => !c.Next) < min)
            {
                min = a;
                minPattern = patten;
            }
            //パターン対象を戻す。
            for (int i = 0; i < aliveNoList.Count(); i++)
            {
                if ((patten & ((UInt64)1 << i)) != 0)
                {
                    data[aliveNoList[i]].IsAlive = true;
                }
            }
            //人数分のパターンが終わったので辞める。
            if ((patten & (((UInt64)1) << aliveNoList.Count())) != 0)
                break;
        }
        //最小パターンで殺す。
        for (int i = 0; i < aliveNoList.Count(); i++)
        {
            if ((minPattern & (((UInt64)1) << i)) != 0)
            {
                data[aliveNoList[i]].IsAlive = false;
            }
        }
    }

    public Point Get(Cell target)
    {
        int idx = data.IndexOf(target);
        if (idx < 0)
            throw new ArgumentException();

        return new Point(idx % Setting.Size, idx / Setting.Size);
    }
    public Cell Get(int x, int y)
    {
        return data[y.Correct() * Setting.Size + x.Correct()];
    }

    public Cell Get(Cell target, int offsetX, int offsetY)
    {
        var pos = Get(target);
        return Get(pos.X + offsetX, pos.Y + offsetY);
    }
}


public class Cell
{
    public CellManager Manager { get; set; }
    public bool IsAlive { get; set; }
    
    public IEnumerable<Cell> Around
    {
        get
        {
            for (int x = -1; x <= 1; x++)
            {
                for (int y