-
Notifications
You must be signed in to change notification settings - Fork 0
/
DNA.java
49 lines (43 loc) · 1.28 KB
/
DNA.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
import processing.core.PApplet;
public class DNA {
String phrase;
String target = "to be or not to be";
char[] genes;
PApplet sketch;
float fitness;
DNA(PApplet sketch) {
this.sketch = sketch;
genes = new char[target.length()];
for (int i = 0; i < genes.length; i++) {
genes[i] = (char) sketch.random(32, 128); //Pick randomly from range of characters.
}
}
void fitness() {
int score = 0;
for (int i = 0; i < genes.length; i++) {
if (genes[i] == target.charAt(i)) {
score++;
}
}
fitness = (float) score / (float) target.length();
}
DNA crossover(DNA partner) {
DNA child = new DNA(this.sketch);
int midpoint = (int) sketch.random(genes.length);
for (int i = 0; i < genes.length; i++) {
if (i > midpoint) child.genes[i] = genes[i];
else child.genes[i] = partner.genes[i];
}
return child;
}
void mutate(float mutationRate) {
for (int i = 0; i < genes.length; i++) {
if (sketch.random(1) < mutationRate) {
genes[i] = (char) sketch.random(32,128);
}
}
}
String getPhrase() {
return new String(genes);
}
}