-
Notifications
You must be signed in to change notification settings - Fork 0
/
Genome.java
60 lines (46 loc) · 1.2 KB
/
Genome.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
50
51
52
53
54
55
56
57
58
59
60
package grah8384;
import java.io.Serializable;
import java.util.Random;
import spacesettlers.simulator.Toroidal2DPhysics;
import spacesettlers.utilities.Position;
public class Genome implements Comparable<Genome>{
protected static Genome maxFit = null;
protected double fitness;
protected double x, y;
public Genome(double x, double y) {
this.x = x;
this.y = y;
this.fitness = Double.NEGATIVE_INFINITY;
}
public void mutate(double mutRate, Toroidal2DPhysics space) {
Random rand = new Random();
if (rand.nextDouble() < mutRate) {
double dist = space.findShortestDistance(new Position(x, y), new Position(maxFit.x, maxFit.y));
x += rand.nextGaussian()*dist;
y += rand.nextGaussian()*dist;
}
toroidalWrap(space);
}
@Override
public int compareTo(Genome o) {
//-1 so default sort does descending
return -1 *Double.compare(fitness, o.fitness);
}
/**
* Torridial wrap based on the height/width of the enviroment
*
* @param position
*/
void toroidalWrap(Toroidal2DPhysics space) {
int width = space.getWidth();
int height = space.getHeight();
while (x < 0) {
x = x + width;
}
while (y < 0) {
y = y + height;
}
x = x % width;
y = y % height;
}
}