From 1a46936216734a2a8e5abe852505a67a5bba1f4a Mon Sep 17 00:00:00 2001 From: Sam Hadow Date: Fri, 18 Oct 2024 11:37:16 +0200 Subject: [PATCH] genetic algorithm implementation --- genetic-algorithm.py | 24 ++++++++++++++++++++++++ 1 file changed, 24 insertions(+) diff --git a/genetic-algorithm.py b/genetic-algorithm.py index 8501840..928211f 100644 --- a/genetic-algorithm.py +++ b/genetic-algorithm.py @@ -18,3 +18,27 @@ def mutation(solution, k): i = random.randint(0,len(solution)-1) solution[i] = random.choice(list({i for i in range(k)} - {solution[i]})) return solution + +def genetic(problem_data, k, popsize, mutation_chance, stop, reproduce): + population = generate_initial_population(problem_data, k, popsize) + population.sort(key = lambda x : fitness(x, problem_data, k), reverse=True) + loop = 0 + while loopx else offspring) + population = sorted(population + new, key=lambda x: fitness(x, problem_data, k), reverse=True)[-4:] + + new_best = fitness(population[-1], problem_data, k) + loop = loop + 1 if best<=new_best else 0 + best = new_best + + return(population[-1]) + +ans = genetic(tasks, 2, 4, 0.2, 10, 4) +print(ans) +print(fitness(ans, tasks, 2))