static void GeneticAlgorithm(string outFileName, Field field, int screenWidth, Random random, uint genomLength = 1000, uint groupSize = 10) { // ほげる if (groupSize % 2 != 0) { throw new Exception("AAN"); } List <KeyValuePair <int, bool> > maxScores = new List <KeyValuePair <int, bool> >(); // 初期化 List <Genom> genoms = new List <Genom>(); for (int i = 0; i < groupSize; i++) { genoms.Add(Genom.Init(genomLength, random)); } List <double> scoreAvgs = new List <double>(); for (int c = 0; c < 3000; c++) { List <int> scores = new List <int>(); // 評価 for (int i = 0; i < groupSize; i++) { Genom genom = genoms.ElementAt(i); Simulator simulator = new Simulator(field, screenWidth); while (!simulator.End && !genom.End) { //simulator.Draw(); //System.Threading.Thread.Sleep(100); Action nextAction = genom.Next(); simulator.Update(nextAction); } genom.IsClear = simulator.IsClear; genom.Score = simulator.Score; //Console.Clear(); //Console.SetCursorPosition(0, 20); //Console.WriteLine("GENERATION:{0}", c); //Console.WriteLine("SCORE:{0}", genom.Score); scores.Add(genom.Score); if (maxScores.Count < 10) { maxScores.Add(new KeyValuePair <int, bool>(genom.Score, genom.IsClear)); maxScores.Sort((a, b) => a.Key.CompareTo(b.Key)); } else if (maxScores[0].Key < genom.Score) { maxScores.Add(new KeyValuePair <int, bool>(genom.Score, genom.IsClear)); maxScores = maxScores.OrderByDescending(a => a.Key).Take(10).OrderBy(a => a.Key).ToList(); } } scoreAvgs.Add(scores.Average()); // 次世代 genoms = NextGeneration(genoms); } using (StreamWriter sw = new StreamWriter(outFileName)) { maxScores.Reverse(); sw.WriteLine("{0} / {1} was goal", maxScores.OrderByDescending(a => a.Key).Take(10).Where(a => a.Value).Count(), 10); foreach (var scoreAvg in scoreAvgs) { sw.WriteLine("{0}", scoreAvg); } } }