}//获得当前种群的最优适应度 public void Initializer(ref GAChromosome GAChro) { int flag1 = 0; int flag2 = 1; double flag3; while (flag2 == 1) { for (int i = 0; i < n; i++) { flag3 = m_Random.NextDouble(); if (flag3 > 0.5 && flag1 != p) { GAChro.Add(1); flag1++; } else { GAChro.Add(0); } } if (flag1 == p) { flag2 = 0; } else { GAChro.Clear(); flag1 = 0; } } }//染色体初始化
}//染色体初始化 public void Initializer1(ref GAChromosome GAChro) { List <int> ones = new List <int>(); ones.Clear(); while (ones.Count < p) { int temp = m_Random.Next(0, n); bool flag = true; for (int i = 0; i < ones.Count; i++) { if (temp == ones[i]) { flag = false; continue; } } if (flag) { ones.Add(temp); } } GAChro.Clear(); for (int i = 0; i < n; i++) { bool flag = true; for (int j = 0; j < ones.Count; j++) { if (ones[j] == i) { GAChro.Add(1); ones.Remove(i); flag = false; } } if (flag) { GAChro.Add(0); } } }
public void CrossOver(GAChromosome Dad, GAChromosome Mum, ref GAChromosome child1, ref GAChromosome child2) { int countDad = 0, countMum = 0; List <int> crosspoint = new List <int>(); for (int i = 0; i < n; i++) { if (Dad[i] == 1) { countDad++; } if (Mum[i] == 1) { countMum++; } if (countDad == countMum) { crosspoint.Add(i); } ; } switch (Crosstype = 1) { //一点交叉 case 1: { int count = crosspoint.Count(); int j = ((int)m_Random.Next(0, count)); int index = (int)crosspoint[j]; for (int k = 0; k < n; k++) { if (k <= index) { child1.Add(Dad[k]); child2.Add(Mum[k]); } else { child1.Add(Mum[k]); child2.Add(Dad[k]); } } break; } //多点交叉 case 2: { for (int i = 0; i < crosspoint.Count; i++) { if (m_Random.NextDouble() > 0.5) { for (int k = crosspoint[i]; k < crosspoint[i + 1]; k++) { child1.Add(Dad[k]); child2.Add(Mum[k]); } } else { for (int k = crosspoint[i]; k < crosspoint[i + 1]; k++) { child1.Add(Mum[k]); child2.Add(Dad[k]); } } } break; } } }//交叉