List<String> beginlist = new ArrayList<>(); List<String> list = new ArrayList<>(); for (int i = 0; i < beginsum; i++) { String s = randomlist(); beginlist.add(s);
}
System.out.println(beginlist); int iter = 0; while (iter < 1000) {
Iterator<String> iterator = beginlist.iterator(); while (iterator.hasNext()) { String str = iterator.next(); if (!isLegal(str)) { iterator.remove(); } }
int len = beginlist.size();
double fitsum = 0; double[] cp = newdouble[beginsum];//累积概率cp int[] select = newint[beginsum]; for (int i = 0; i < len; i++) { fitsum = fitsum + fitness(beginlist.get(i)); //求适应度之和fitsum }
for (int i = 0; i < len; i++) { if (i == 0) { cp[i] = fitness(beginlist.get(i)) / fitsum; } else { cp[i] = cp[i - 1] + fitness(beginlist.get(i)) / fitsum; //求累积概率 }
}
//筛选 for (int i = 0; i < beginsum; i++) { double random = Math.random(); int j = 0; while (cp[j] < random) { j++; } select[j]++; //选择次数 } for (int i = 0; i < beginsum; i++) { Random r = new Random(); int random = r.nextInt(beginsum); while (select[random] == 0) { random = r.nextInt(beginsum); } list.add(beginlist.get(random));//选择优秀个体 select[random]--; }
//交叉 //随机配对 boolean[] cross = newboolean[beginsum]; int[][] arr = newint[beginsum/2][2];//配对数组 for (int i = 0; i < beginsum/2; i++) { for (int j = 0; j < 2; j++) { Random r = new Random(); int random = r.nextInt(beginsum); while (cross[random] == true) { random = r.nextInt(beginsum); } cross[random] = true; arr[i][j] = random; }
}
//交换基因片段 for (int i = 0; i < 5; i++) { Random r = new Random(); String str, str1; int random = r.nextInt(5);//随机设置交叉点位置 str = list.get(arr[i][0]); str1 = list.get(arr[i][1]); String strsub = str.substring(0, random), strsub1 = str.substring(random), str1sub = str1.substring(0, random), str1sub1 = str1.substring(random); str = strsub + str1sub1; str1 = str1sub + strsub1;
publicstaticbooleanisLegal(String str){ int sum = 0, num; for (int i = 0; i < 5; i++) { num = str.charAt(i) - '0'; sum = sum + num * w[i]; } if (sum > 10) returnfalse; returntrue; }
/** * 初始化个体 * * @return */ publicstatic String randomlist(){ String str = ""; for (int i = 0; i < 5; i++) { int num = Math.random() > 0.5 ? 1 : 0;//随机产生1,0 str += String.valueOf(num); } return str; }
/** * 计算适应度 * * @param n * @return */ publicstaticintfitness(String str){ int sum = 0, num; for (int i = 0; i < 5; i++) { num = str.charAt(i) - '0'; sum = sum + num * v[i]; } return sum; }