|
| 1 | +package DataMining_ACO; |
| 2 | + |
| 3 | +import java.util.ArrayList; |
| 4 | + |
| 5 | +/** |
| 6 | + * 蚂蚁类,进行路径搜索的载体 |
| 7 | + * |
| 8 | + * @author lyq |
| 9 | + * |
| 10 | + */ |
| 11 | +public class Ant implements Comparable<Ant>{ |
| 12 | + //蚂蚁当前所在城市 |
| 13 | + String currentPos; |
| 14 | + // 蚂蚁遍历完回到原点所用的总距离 |
| 15 | + Double sumDistance; |
| 16 | + // 城市间的信息素浓度矩阵,随着时间的增多而减少 |
| 17 | + double[][] pheromoneMatrix; |
| 18 | + // 蚂蚁已经走过的城市集合 |
| 19 | + ArrayList<String> visitedCitys; |
| 20 | + // 还未走过的城市集合 |
| 21 | + ArrayList<String> nonVisitedCitys; |
| 22 | + // 蚂蚁当前走过的路径 |
| 23 | + ArrayList<String> currentPath; |
| 24 | + |
| 25 | + public Ant(double[][] pheromoneMatrix, ArrayList<String> nonVisitedCitys) { |
| 26 | + this.pheromoneMatrix = pheromoneMatrix; |
| 27 | + this.nonVisitedCitys = nonVisitedCitys; |
| 28 | + |
| 29 | + this.visitedCitys = new ArrayList<>(); |
| 30 | + this.currentPath = new ArrayList<>(); |
| 31 | + } |
| 32 | + |
| 33 | + /** |
| 34 | + * 计算路径的总成本(距离) |
| 35 | + * |
| 36 | + * @return |
| 37 | + */ |
| 38 | + public double calSumDistance() { |
| 39 | + sumDistance = 0.0; |
| 40 | + String lastCity; |
| 41 | + String currentCity; |
| 42 | + |
| 43 | + for (int i = 0; i < currentPath.size() - 1; i++) { |
| 44 | + lastCity = currentPath.get(i); |
| 45 | + currentCity = currentPath.get(i + 1); |
| 46 | + |
| 47 | + // 通过距离矩阵进行计算 |
| 48 | + sumDistance += ACOTool.disMatrix[Integer.parseInt(lastCity)][Integer |
| 49 | + .parseInt(currentCity)]; |
| 50 | + } |
| 51 | + |
| 52 | + return sumDistance; |
| 53 | + } |
| 54 | + |
| 55 | + /** |
| 56 | + * 蚂蚁选择前往下一个城市 |
| 57 | + * @param city |
| 58 | + * 所选的城市 |
| 59 | + */ |
| 60 | + public void goToNextCity(String city){ |
| 61 | + this.currentPath.add(city); |
| 62 | + this.currentPos = city; |
| 63 | + this.nonVisitedCitys.remove(city); |
| 64 | + this.visitedCitys.add(city); |
| 65 | + } |
| 66 | + |
| 67 | + /** |
| 68 | + * 判断蚂蚁是否已经又重新回到起点 |
| 69 | + * @return |
| 70 | + */ |
| 71 | + public boolean isBack(){ |
| 72 | + boolean isBack = false; |
| 73 | + String startPos; |
| 74 | + String endPos; |
| 75 | + |
| 76 | + if(currentPath.size() == 0){ |
| 77 | + return isBack; |
| 78 | + } |
| 79 | + |
| 80 | + startPos = currentPath.get(0); |
| 81 | + endPos = currentPath.get(currentPath.size()-1); |
| 82 | + if(currentPath.size() > 1 && startPos.equals(endPos)){ |
| 83 | + isBack = true; |
| 84 | + } |
| 85 | + |
| 86 | + return isBack; |
| 87 | + } |
| 88 | + |
| 89 | + @Override |
| 90 | + public int compareTo(Ant o) { |
| 91 | + // TODO Auto-generated method stub |
| 92 | + return this.sumDistance.compareTo(o.sumDistance); |
| 93 | + } |
| 94 | +} |
0 commit comments