遺傳算法模擬生物進化進行優化搜索,主循環包含:初始種群 → 適應度計算 → 選擇 → 交叉 → 變異 → 迭代直到最優解。本實現採用接口分離策略,核心類包括Population(種群)與Individual(個體)。
繼承CollectionBase,實現ICloneable/IDisposable,主要職責:
Init(int max)生成指定數量隨機基因個體(22位二進制串)。MaxFitness、AverageFitness、SumFitness即時反映種群優劣。IGeneticStrategy接口,動態注入選擇/交叉/變異具體實現。Select()/Crossover()/Mutation()轉調策略對象。Gene屬性(二進制字符串),設置時自動計算適應度(_calFit.Fitness(Variable))。Variable屬性通過Coder.ToReal(Gene, -1.0, 2.0)映射為[-1,2]實數域。operator *實現單點交叉,隨機選擇片段互換,確保片段不同。Mutation()隨機翻轉一位基因(0↔1)。// 交叉核心邏輯
public static int operator *(Individual ind1, Individual ind2) {
Random rd = new Random();
int iStart = rd.Next(0, ind1.Gene.Length-2);
int iLast = rd.Next(iStart+1, ind1.Gene.Length-1);
while (ind1.Gene.Substring(iStart, iLast-iStart) == ind2.Gene.Substring(iStart, iLast-iStart)) {
iStart = rd.Next(0, ind1.Gene.Length-2);
iLast = rd.Next(iStart+1, ind1.Gene.Length-1);
}
// 片段互換生成新基因...
return iLast - iStart;
}
// 變異
public int Mutation() {
int iPos = new Random().Next(0, Gene.Length-1);
var sb = new StringBuilder(Gene);
sb[iPos] = sb[iPos] == '0' ? '1' : '0';
Gene = sb.ToString();
return iPos;
}
框架採用策略模式解耦演化邏輯,支持自定義適應度函數(IFitness)與選擇/交叉/變異策略,具備良好擴展性。