Change metric in Greedy algorithm

This commit is contained in:
coolneng 2021-04-13 22:43:45 +02:00
parent b63b5b08b6
commit 75c3a94fbe
Signed by: coolneng
GPG Key ID: 9893DA236405AF57
1 changed files with 11 additions and 11 deletions

View File

@ -25,16 +25,18 @@ def get_different_element(original, row):
return row.source return row.source
def get_furthest_element(element, data): def get_closest_element(element, data):
element_df = data.query(f"source == {element} or destination == {element}") element_df = data.query(f"source == {element} or destination == {element}")
furthest_index = element_df["distance"].astype(float).idxmax() closest_index = element_df["distance"].astype(float).idxmin()
furthest_row = data.iloc[furthest_index] closest_row = data.loc[closest_index]
furthest_point = get_different_element(original=element, row=furthest_row) closest_point = get_different_element(original=element, row=closest_row)
return Series(data={"point": furthest_point, "distance": furthest_row["distance"]}) return Series(data={"point": closest_point, "distance": closest_row["distance"]})
def remove_solution_dataset(data, solution): def explore_solutions(solutions, data):
return data.query(f"source != {solution} and destination != {solution}") closest_elements = solutions["point"].apply(func=get_closest_element, data=data)
furthest_index = closest_elements["distance"].astype(float).idxmax()
return closest_elements.iloc[furthest_index]
def greedy_algorithm(n, m, data): def greedy_algorithm(n, m, data):
@ -42,10 +44,8 @@ def greedy_algorithm(n, m, data):
first_solution = get_first_solution(n, data) first_solution = get_first_solution(n, data)
solutions = solutions.append(first_solution, ignore_index=True) solutions = solutions.append(first_solution, ignore_index=True)
for _ in range(m): for _ in range(m):
last_solution = int(solutions["point"].tail(n=1)) element = explore_solutions(solutions, data)
centroid = get_furthest_element(element=last_solution, data=data) solutions = solutions.append(element)
solutions = solutions.append(centroid, ignore_index=True)
data = remove_solution_dataset(data=data, solution=last_solution)
return solutions return solutions