http://i.imgur.com/PWVruQ0.png
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package parentmutation;
import java.util.ArrayList;
import java.util.Random;
/**
*
* @author Renter
*/
public class Parentmutation {
/**
* @param args the command line arguments
*/
static int population = 50;
static int geneSize = 25;
public static void main(String[] args) {
char[] parenta = new char[geneSize]; //Create parents to pull genes from
for (int x = 0; x < geneSize; x++) {
parenta[x] = 'A';
System.out.print("-");
}
System.out.println();
char[] parentb = new char[geneSize];
for (int x = 0; x < geneSize; x++) {
parentb[x] = 'B';
}
char[][] people = new char[population][]; //How many children to make
Parentmutation p = new Parentmutation();
for (int x = 0; x < population; x++) {
people[x] = p.flopChild(parenta, parentb); //Save it for later
System.out.println(people[x]); //Output it for now
}
}
public char[] flopChild(char[] a, char[] b) {
Random r = new Random();
int y = 0;
ArrayList<Integer> parts = new ArrayList();
char[] child = new char[geneSize];
while (y < geneSize) { //Break it into parts so you can easily swap genes from the parents
int num = r.nextInt(geneSize + 1 - y);
if (num + y > geneSize) {
parts.add(num + y - geneSize);
y = geneSize + 1;
} else {
if (num == 0) {
} else {
parts.add(num);
y += num;
}
}
}
int last = 0;
for (int x = 0; x < parts.size(); x++) { //Use the pieces to get chunks from the parents var a and b
for (int z = last; z < last + parts.get(x); z++) {
if (r.nextInt(2) == 0) { //Decied which parent to pull from
child[z] = a[z];
} else {
child[z] = b[z];
}
}
last = parts.get(x);
}
return child;
}
}
所以我试图创建一些基于两个父母的孩子。目标是将具有“AAAAAA”特征的父母a和具有“BBBBB”特征的父母b随机分配给孩子。结果看起来像“ABABA”、“AAAAB”或它们的任何其他组合。我现在拥有的代码交换了特征并将它们返回给孩子,但它们并不总是正确的长度。我包含的代码只运行一次以简化事情。以下是一些示例结果。
run:
-------------------------
ABBBBABBBBABAABABBBAAAB
BBAAAAABABBBBABAAAAAA
BAAAAAABABBBB
BAAAABBAABBABABAABBABABBB
BBAAAAABBABBABAABBA
BAABBAAABBAABBBAAAABAAAB
BBABABAABABAABBBBBAAAA
BBBBABAAAABBBBBAABBAA
ABAABBABBBBBAAABABBABAAB