com2014-template/template/model/my_model_DPD.py

60 lines
1.8 KiB
Python

import math
import random
from model.base_model import Model
class MyDPDModel(Model):
def __init__(self):
super().__init__()
def init(self, nodes):
"""
Put your initialization here.
"""
super().init(nodes)
def getMST(self, node):
MST = []
distances = []
for i in range(0, self.N):
if i != node:
MST.append(i)
distances.append(self.dist(node, i))
return [x for _,x in sorted(zip(distances, MST))]
def fit(self, max_it=1000):
"""
Put your iteration process here.
"""
MST_solutions = []
# Depth First: Set one city as starting point, iterate to the end, then select next city as starting point.
MSTs = []
for i in range(0, self.N):
MSTs.append([-1] * self.N)
for i in range(0, self.N):
solution = []
solution.append(i)
unvisited_list = list(range(0, self.N))
cur_city = i
# print("[starting]", i)
for steps in range(self.N - 1):
# print(unvisited_list)
unvisited_list.remove(cur_city)
if MSTs[cur_city][0] == -1:
MST = self.getMST(cur_city)
MSTs[cur_city] = MST
for j in MSTs[cur_city]:
if(j in unvisited_list):
solution.append(j)
cur_city = j
break
# print(solution)
MST_solutions.append(solution)
self.fitness_list.append(self.fitness(solution))
self.best_solution = MST_solutions[ self.fitness_list.index(min(self.fitness_list)) ]
return self.best_solution, self.fitness_list