Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- public static class Program
- {
- static int populationCount = 100;
- static int width = 400;
- static int height = 400;
- static Random r = new Random();
- static float tx = 50;
- //static float tx = (float)Math.Round((double)r.Next(-width, width)/10, 2);
- //static float ty = (float)Math.Round((double)r.Next(-height, height)/10, 2);
- static Creature[] population = new Creature[populationCount];
- public static void Main()
- {
- Generations(5);
- }
- static void Generations(int n)
- {
- List<Creature> matingpool = new List<Creature>(new Creature[populationCount]);
- population = CreatePopulation(population);
- for(int _ = 0; _ < n; _++)
- {
- Console.WriteLine("\nGeneration: {0}", _);
- for(int i = 0; i < population.Length; i++)
- {
- Creature c = population[i];
- c.Live();
- float cfit = Math.Abs(1/CheckDist(c.x, 0/*c.y*/));
- AddToMP(cfit, matingpool, c.dna, null);
- }
- Creature bestCreature = GetNearestCreature(population);
- foreach(Creature c in population)
- //Console.WriteLine(c.x);
- AddToMP(null, matingpool, null, bestCreature.dna);
- Console.WriteLine("Best Creature position: x={0}, y={1}", bestCreature.x, 0/*bestCreature.y*/);
- Console.WriteLine("Target position: x={0}, y={1}", tx, 0/*ty*/);
- population = Reproduce(matingpool, population);
- }
- }
- static void AddToMP(float? chance, List<Creature> mp, List<float> cdna, List<float> bdna)
- {
- if(bdna == null)
- {
- chance = (int) chance * 20;
- for(int i = 0; i < chance && mp.Count < population.Length; i++)
- {
- mp[i] = new Creature(cdna);
- }
- }
- else
- {
- mp[0] = new Creature(bdna);
- while(mp.Count < population.Length)
- {
- mp.Add(new Creature(null));
- }
- }
- }
- static Creature[] Reproduce(List<Creature> mp, Creature[] popul)
- {
- for(int i = 0; i < mp.Count; i++)
- popul[i] = mp[i];
- return popul;
- }
- static Creature[] CreatePopulation(Creature[] pop)
- {
- for(int i = 0; i < populationCount; i++)
- {
- pop[i] = new Creature(null);
- }
- return pop;
- }
- static Creature GetNearestCreature(Creature[] popul)
- {
- float recordDist = 10000;
- int recordCreatureIndex = 0;
- for(int i = 0; i < popul.Length; i++)
- {
- float distance = CheckDist(popul[i].x, popul[i].y);
- if(distance < recordDist)
- {
- recordDist = distance;
- recordCreatureIndex = i;
- }
- }
- return popul[recordCreatureIndex];
- }
- static float CheckDist(float x, float y)
- {
- float dx = tx - x;
- return dx;
- //float dy = ty - y;
- //float dist = (dx + dy) / 2;
- //return dist;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement