Comment detail

ライフゲーム (Nested Flatten)

初投稿です。 長いコードですが、自分は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 = -1; y <= 1; y++)
                {
                    if (x == 0 && y == 0)
                        continue;
                    yield return Manager.Get(this, x, y);
                }
            }
        }
    }
    public int AroundAliveCount
    {
        get
        {
            return Around.Count(cell => cell.IsAlive);
        }
    }
    public bool Next
    {
        get
        {
            return IsAlive ?
                AroundAliveCount == 2 || AroundAliveCount == 3 :
                AroundAliveCount == 3;
        }
    }
}

Index

Feed

Other

Link

Pathtraq

loading...