Remove redundant previous solution checks

This commit is contained in:
coolneng 2021-04-19 18:25:53 +02:00
parent bd4a88bb4e
commit 097ed9b52a
Signed by: coolneng
GPG Key ID: 9893DA236405AF57
1 changed files with 5 additions and 21 deletions

View File

@ -17,28 +17,12 @@ def replace_worst_element(previous, data):
return solution, worst_index return solution, worst_index
def choose_best_solution(previous, current, index):
if previous.loc[index].distance >= current.loc[index].distance:
return previous
return current
def get_random_solution(previous, data): def get_random_solution(previous, data):
candidates = []
candidates.append(previous)
solution, worst_index = replace_worst_element(previous, data) solution, worst_index = replace_worst_element(previous, data)
previous_worst_distance = previous["distance"].loc[worst_index] previous_worst_distance = previous["distance"].loc[worst_index]
last_solution = candidates[-1] while solution.distance.loc[worst_index] <= previous_worst_distance:
while last_solution.distance.loc[worst_index] <= previous_worst_distance:
solution, _ = replace_worst_element(previous=solution, data=data) solution, _ = replace_worst_element(previous=solution, data=data)
if solution.equals(last_solution): return solution
best_solution = choose_best_solution(
previous=previous, current=solution, index=worst_index
)
return best_solution
candidates.append(solution)
last_solution = candidates[-1]
return last_solution
def explore_neighbourhood(element, data, max_iterations=100000): def explore_neighbourhood(element, data, max_iterations=100000):
@ -48,13 +32,13 @@ def explore_neighbourhood(element, data, max_iterations=100000):
print(f"Iteration {i}") print(f"Iteration {i}")
previous_solution = neighbourhood[-1] previous_solution = neighbourhood[-1]
neighbour = get_random_solution(previous=previous_solution, data=data) neighbour = get_random_solution(previous=previous_solution, data=data)
if neighbour.equals(previous_solution):
break
neighbourhood.append(neighbour) neighbourhood.append(neighbour)
return neighbour return neighbour
def local_search(m, data): def local_search(m, data):
first_solution = get_first_random_solution(m=m, data=data) first_solution = get_first_random_solution(m=m, data=data)
best_solution = explore_neighbourhood(element=first_solution, data=data) best_solution = explore_neighbourhood(
element=first_solution, data=data, max_iterations=100
)
return best_solution return best_solution