private StringBuilder combine(ga_struct chromo1, ga_struct chromo2) { int tsize = GA_TARGET.Length, spos; spos = rand() % tsize; return(new StringBuilder(chromo1.str.ToString().Substring(0, spos) + chromo2.str.ToString().Substring(spos, tsize - spos))); }
private void mutate(ga_struct member) { int tsize = GA_TARGET.Length; int ipos = rand() % tsize; int delta = (rand() % 90) + 32; member.str[ipos] = (char)((member.str[ipos] + delta) % 122); }
/*private ga_struct select(GAVector population, int tournamentSize, double p) * { * // Select members for the tournament at random from the population * GAVector tournamentMembers = new GAVector(); * for (int i = 0; i < tournamentSize; ++i) * { * int index = rand() % GA_POPSIZE; * tournamentMembers.Add(population[index]); * } * * // Now select from the tournament members using probability p * //double powerBase = (1 / (1-p)); * //int maxIndex = (int)Math.Pow(powerBase, tournamentSize); * //int randomIndex = (rand() % maxIndex) + 1; * //ga_struct selected = null; * //for (int n=tournamentSize-1; n>=0; --n) * //{ * // if (randomIndex >= Math.Pow(powerBase, n)) * // { * // selected = tournamentMembers[n]; * // break; * // } * //} * * sort_by_fitness(tournamentMembers); * * ga_struct selected = null; * for (int i=0; i<tournamentSize; ++i) * { * if (_rand.NextDouble() < p) * { * selected = tournamentMembers[i]; * break; * } * } * selected = selected ?? tournamentMembers[0]; * * //Debug.Assert(selected != null); * * return selected; * }*/ private ga_struct select(GAVector population, int tournamentSize, double p) { ga_struct selected = null; int maxIncrement = GA_POPSIZE / tournamentSize; int index = rand() % maxIncrement; for (int i = 0; i < tournamentSize; ++i) { if (_rand.NextDouble() < p) { selected = population[index]; break; } index += rand() % maxIncrement; } selected = selected ?? population[0]; //Debug.Assert(selected != null); return(selected); }
private void init_population(GAVector population, GAVector buffer) { int tsize = GA_TARGET.Length; for (int i = 0; i < GA_POPSIZE; ++i) { ga_struct citizen = new ga_struct(); citizen.fitness = 0; citizen.str.Clear(); for (int j = 0; j < tsize; ++j) { int charValue = (rand() % 90) + 32; citizen.str.Append((char)charValue); } population.Add(citizen); } buffer.resize(GA_POPSIZE); //var temp = new ga_struct[GA_POPSIZE]; //buffer = temp.ToList<ga_struct>(); }