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))