dijkstra: add statistics for time and co2

This commit is contained in:
Marco Thomas
2022-07-27 17:35:49 +02:00
parent de34b3acce
commit 68885ff560
4 changed files with 43 additions and 19 deletions

View File

@@ -12,10 +12,12 @@ class Dijkstra():
self.graph = graph
self.table = {}
for vertex in graph:
self.table.update({vertex: {"distance": 9999999, "prev": None}})
self.table[connection[0]]["distance"] = 0
self.table.update({vertex: {"distance": (9999999, 999999), "prev": None}})
self.table[connection[0]]["distance"] = (0, 0)
def algorithm(self, switch: str):
assert(switch == "time" or switch == "co2")
def algorithm(self):
print("Performing Dijkstra on the following graph...")
for vertex in self.graph:
print(f"{vertex}: {self.graph[vertex]}")
@@ -24,12 +26,20 @@ class Dijkstra():
neighbors = self.graph[v1]
for n in neighbors:
key = [elem for elem in n.keys()][0] # name of neighbor node
# NOTE: change time or co2 here
edge = n[key]["time"]
dist = self.table[v1]["distance"] + edge
if dist < self.table[key]["distance"]:
self.table[key]["distance"] = dist
self.table[key]["prev"] = v1
edge = (n[key]["time"], n[key]["co2"])
# update both time and co2
time = self.table[v1]["distance"][0] + edge[0]
co2 = self.table[v1]["distance"][1] + edge[1]
# but only eval the one we want
if switch == "time":
if time < self.table[key]["distance"][0]:
self.table[key]["distance"] = (time, co2)
self.table[key]["prev"] = v1
elif switch == "co2":
if co2 < self.table[key]["distance"][1]:
self.table[key]["distance"] = (time, co2)
self.table[key]["prev"] = v1
print("self.table:", self.table)
@@ -39,10 +49,17 @@ class Dijkstra():
# start at destination
sequence.append(dest)
total_time = 0
total_co2 = 0
while start not in sequence:
# previous jump
prev = self.table[sequence[-1]]["prev"]
current = self.table[sequence[-1]] # last element of list
prev = current["prev"]
total_time += current["distance"][0]
total_co2 += current["distance"][1]
sequence.append(prev)
sequence.reverse()
print(sequence)
print("Total Time:", total_time)
print("Total CO2:", total_co2)