/// 种群最大数 let populationMaxCount = 100; /// 种群被筛选后剩余最小数 let populationMinCount = 30;
/// 每个 unit 特征个数 let unitDNACount = 100; /// 突变概率, 20 代表 20% , 即: 生成model会产生突变的概率; let mutationRate = 60;
/// 算法按 相同 算还是 相似 算 let isEqualCount = true;
/// 输出结果是按 线 输出还是按 点 输出 let isDrawLine = false;
主要循环 :
繁衍生息 >> 排序 >> 剔除不像的 >> 输出最像的 >> 是否继续 >> 繁衍生息
1 2 3 4 5 6 7 8 9 10
func runLoop(block:(_ datas:[HeredityModel] , _ times:Int)->Bool) { var isGoOn = true; while isGoOn { makeChilds(); sort(); weedOut(); times += 1; isGoOn = block(datas,times); } }
繁衍生息
当少于种群最大值时就繁殖
在剩余种群中 找出一对父母 进行繁育
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
// 繁衍生息 func makeChilds() { while datas.count < populationMaxCount - 1 { birthChild(); } } // 造人 func birthChild() { let half = populationMinCount / 2; let mother = datas[Int(arc4random()) % half]; // 前半数组中取一个 let father = datas[Int(arc4random()) % half + half]; // 后半数组中取一个 let child = HeredityModel(father, mother); child.makeLikeCount(base: baseModel); datas.append(child); }
造物过程
取父与母的随机一个 DNA 进行遗传 (遗传学中 DNA 是根据显性与隐性来遗传的, 代码中就用随机来代表了)
根据概率计算其是否需要变异 (没有变异, 物种就不会进化)
随机计算要进化的 DNA 的位置
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
init(_ model1:HeredityModel ,_ model2:HeredityModel) { let isMutation = arc4random() % 100 < mutationRate; //是否进行突变 let index = isMutation ? Int(arc4random()) % unitDNACount : -1; // 突变位置 for i in 0...unitDNACount-1 { if i == index { // 突变 models.append(HereditySubModel()); } else { // 正常遗传 let random = arc4random() % 2; let model = random == 1 ? model2 : model1; models.append(model.models[i]); } } }