public double[] GeneticMaximum() { GeneticBrain thisBrain = new GeneticBrain(); const int numWalkers = 500; double[] final = new double[2]; Random rnd = new Random(); int stepIndex = new int(); // Define a number of walkers on the field to be bred. GeneticWalker[] walkers = new GeneticWalker[numWalkers]; // Initialize the walkers. for (int i = 0; i < numWalkers; i++) walkers[i] = new GeneticWalker(); for (int walkerIndex = 0; walkerIndex < numWalkers; walkerIndex++) { for (stepIndex = 0; stepIndex < walkers[walkerIndex].walkerHistory.Length; stepIndex++) { int step = rnd.Next(0, 3) - 1; if (rnd.Next(0, 2) == 1) { walkers[walkerIndex].walkerPosition[0] += step * walkers[walkerIndex].dx; walkers[walkerIndex].walkerHistory[stepIndex] = new Complex(step * walkers[walkerIndex].dx, 0); } else { walkers[walkerIndex].walkerPosition[1] += step * walkers[walkerIndex].dx; walkers[walkerIndex].walkerHistory[stepIndex] = new Complex(0, step * walkers[walkerIndex].dx); } } walkers[walkerIndex].height = walkers[walkerIndex].walkerHeight(); } thisBrain.SortWalkers(ref walkers); for (int i = 0; i < 1500; i++ ) { GeneticWalker[] temp = walkers; thisBrain.SortWalkers(ref temp); thisBrain.BreedWalkers(ref walkers); thisBrain.WalkFromHistory(ref walkers); thisBrain.SortWalkers(ref walkers); if (temp[0].height > walkers[0].height) walkers = temp; Console.WriteLine(Convert.ToString(i)+": "+Convert.ToString(Math.Sqrt(Math.Pow(walkers[0].walkerPosition[0]-3.4,2)+Math.Pow(walkers[0].walkerPosition[1]+4,2)))); } thisBrain.SortWalkers(ref walkers); final = walkers[0].walkerPosition; return final; }
public void BreedWalkers(ref GeneticWalker[] walkers) { GeneticWalker[] walkerClones = walkers; Random rnd = new Random(); for (int walkerIndex = 0; walkerIndex < walkers.Length; walkerIndex += 2 ) for (int switchLocation = rnd.Next(0, walkers[0].walkerHistory.Length-1); switchLocation < walkers[0].walkerHistory.Length; switchLocation++) { walkers[walkerIndex].walkerHistory[switchLocation] = walkers[walkerIndex+1].walkerHistory[switchLocation]; walkers[walkerIndex + 1].walkerHistory[switchLocation] = walkerClones[walkerIndex].walkerHistory[switchLocation]; } }
public void WalkFromHistory(ref GeneticWalker[] walkers) { for(int index = 0; index < walkers.Length; index++) { walkers[index].height = walkers[index].walkerHeight(); walkers[index].walkerPosition[0] = 0; walkers[index].walkerPosition[1] = 0; for(int j = 0; j < walkers[index].walkerHistory.Length; j++) { walkers[index].walkerPosition[0] += walkers[index].walkerHistory[j].Real; walkers[index].walkerPosition[1] += walkers[index].walkerHistory[j].Imaginary; } } }
// Sort the walkers by the final values of their height after their walk. public void SortWalkers(ref GeneticWalker[] walkers) { Array.Sort(walkers); }