diff --git a/src/genetic_algorithm.py b/src/genetic_algorithm.py index ae587b6..6ce7ffd 100644 --- a/src/genetic_algorithm.py +++ b/src/genetic_algorithm.py @@ -158,15 +158,34 @@ def generational_replacement(previous_population, current_population): return new_population -def stationary_replacement(previous_population, current_population): - new_population = previous_population +def get_best_elements(population): + first_index = population.index(max(population, key=lambda x: x.fitness)) + population.pop(first_index) + second_index = population.index(max(population, key=lambda x: x.fitness)) + return first_index, second_index + + +def get_worst_elements(population): + first_index = population.index(min(population, key=lambda x: x.fitness)) + population.pop(first_index) + second_index = population.index(min(population, key=lambda x: x.fitness)) + return first_index, second_index + + +def stationary_replacement(prev_population, current_population): + new_population = prev_population + worst_indexes = get_worst_elements(prev_population) + best_indexes = get_best_elements(current_population) + for worst, best in zip(worst_indexes, best_indexes): + if current_population[best].fitness > prev_population[worst].fitness: + new_population[worst] = current_population[best] return new_population -def replace_population(previous_population, current_population, mode): +def replace_population(prev_population, current_population, mode): if mode == "generational": - return generational_replacement(previous_population, current_population) - return stationary_replacement(previous_population, current_population) + return generational_replacement(prev_population, current_population) + return stationary_replacement(prev_population, current_population) def genetic_algorithm(n, m, data, mode):