using System; >>using System.Collections.Generic; >>using System.Diagnostics; >>using System.Linq; >> >>namespace ConsoleApplication8 >>{ >> class Program >> { >> static readonly List<Person> Population = new List<Person>(); >> static Random r = new Random(); >> static void Main(string[] args) >> { >> >> var adam = new Person( new string('0',256),Sex.Male); >> var eve = new Person( new string('1',256),Sex.Female); >> Population.Add(adam); >> Population.Add(eve); >> try >> { >> Breed(); >> } >> catch (Exception ex) >> { >> Console.WriteLine(string.Format("World is full. Population is {0}",Population.Count)); >> Console.ReadLine(); >> } >> } >> >> static void Breed() >> { >> var females = Population.Where(x => x.Sex == Sex.Female).ToArray(); >> Console.WriteLine(String.Format("Females:{0} Males:{1}",females.Count(), Population.Count()-females.Count())); >> >> List<Person> children = new List<Person>(); >> foreach (Person male in Population.AsParallel().WithExecutionMode(ParallelExecutionMode.ForceParallelism).Where(x => x.Sex == Sex.Male)) >> { >> children.Add(male + females.Skip(r.Next(0, females.Count())).Take(1).First()); >> } >> Population.AddRange(children); >> Console.WriteLine(string.Format("Memory used: {0}Mb",Math.Round((double)Process.GetCurrentProcess().PrivateMemorySize64/1048576))); >> Breed(); >> } >> } >> >> public struct Person >> { >> private readonly string _dna; >> public Sex Sex; >> private static Random r = new Random(); >> public Person(string dna,Sex sex) >> { >> _dna = dna; >> Sex = sex; >> } >> >> public static Person operator +(Person m, Person f) >> { >> var result = new char[256]; >> int mStart = 0; >> int fStart = 128; >> for (var x = 0; x < 256; x += 2) >> { >> result[x] = m._dna[mStart++]; >> result[x + 1] = f._dna[fStart++]; >> } >> return new Person(new String(result), (Sex)Enum.GetValues(typeof(Sex)).GetValue(r.Next(2))); >> } >> } >> >> public enum Sex >> { >> Male, >> Female >> } >>}