http://i.imgur.com/PWVruQ0.png爲什麼我的基因突變密碼不能重新調整整個基因? Java的
/*
* 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;
}
}
所以我想創建一個基於對開家長的孩子。目標是帶着父母a的特徵「AAAAA」和父母b的特質「BBBBB」,並隨機給孩子們。結果看起來像「ABABA」,「AAAAB」或這些的任何其他組合。我現在的代碼已經交換了這些特性,並將它們返回給孩子,但它們並不總是正確的長度。我所包含的代碼只能通過它來簡化一些事情。以下是一些示例結果。
run:
-------------------------
ABBBBABBBBABAABABBBAAAB
BBAAAAABABBBBABAAAAAA
BAAAAAABABBBB
BAAAABBAABBABABAABBABABBB
BBAAAAABBABBABAABBA
BAABBAAABBAABBBAAAABAAAB
BBABABAABABAABBBBBAAAA
BBBBABAAAABBBBBAABBAA
ABAABBABBBBBAAABABBABAAB
請在此處添加您的代碼,並解釋是錯誤。 – BobTheBuilder