-
Notifications
You must be signed in to change notification settings - Fork 0
/
Path.java
76 lines (64 loc) · 1.82 KB
/
Path.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
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
import java.util.ArrayList;
import java.util.Collections;
public class Path{
private ArrayList path = new ArrayList<City>();
private double fitness = 0;
private int distance = 0;
public Path(){
for (int i = 0; i < CityRef.numCities(); i++) {
path.add(null);
}
}
public void randomizePath() {
for (int i = 0; i < CityRef.numCities(); i++) {
setCity(i, CityRef.getCity(i));
}
Collections.shuffle(path);
}
public City getCity(int pathPosition) {
return (City)path.get(pathPosition);
}
public void setCity(int pathPosition, City city) {
path.set(pathPosition, city);
fitness = 0;
distance = 0;
}
public double getFitness() {
if (fitness == 0) {
fitness = 1/(double)getDistance();
}
return fitness;
}
public int pathSize() {
return path.size();
}
public boolean containsCity(City city){
return path.contains(city);
}
public int getDistance(){
if (distance == 0) {
int pathDistance = 0;
for (int i=0; i < pathSize(); i++) {
City originCity = getCity(i);
City destinationCity;
if(i+1 < pathSize()){
destinationCity = getCity(i+1);
}
else{
destinationCity = getCity(0);
}
pathDistance += originCity.distanceTo(destinationCity);
}
distance = pathDistance;
}
return distance;
}
@Override
public String toString() {
String geneString = "";
for (int i = 0; i < pathSize(); i++) {
geneString += getCity(i)+" => ";
}
return geneString;
}
}