-
Notifications
You must be signed in to change notification settings - Fork 0
/
Brain.pde
52 lines (45 loc) · 1.45 KB
/
Brain.pde
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
50
51
52
public class Brain {
String guessPhrase, targetPhrase;
String chars = "abcdefghijklmnopqrstuvwxyz 1234567890;,.?!'"; //add characters if needed
public Brain(String target) {
targetPhrase = target;
guessPhrase = "";
}
//generates the guess phrase
public void makeGuess() {
for (int i = 0; i < targetPhrase.length(); i++) {
int randomIn = (int)random(chars.length());
guessPhrase = guessPhrase.concat(chars.charAt(randomIn) + "");
}
}
public void mutate() {
String g = guessPhrase;
char[] tempArr = g.toCharArray();
float mutationRate = 0.01;
for (int i = 0; i < guessPhrase.length(); i++) {
float rand = random(1);
if (rand < mutationRate) {
tempArr[i] = chars.charAt((int)random(chars.length()));
}
}
g = String.valueOf(tempArr);
guessPhrase = g;
}
//gets genes from two parents
public Brain crossover(Sequencer parentB) {
String guessB = parentB.brain.guessPhrase, guessA = guessPhrase;
Brain newBrain = new Brain(target);
newBrain.makeGuess();
char[] guess = newBrain.guessPhrase.toCharArray();
float mid = random(target.length());
for (int i = 0; i < target.length(); i++) {
if (i < mid) {
guess[i] = guessA.charAt(i);
} else {
guess[i] = guessB.charAt(i);
}
}
newBrain.guessPhrase = String.valueOf(guess);
return newBrain;
}
}