From 3b4bc26cff1dbc8dbd4bcaa6c8be26961e057e3a Mon Sep 17 00:00:00 2001 From: Sam Hadow Date: Fri, 18 Oct 2024 09:44:43 +0200 Subject: [PATCH] initial pop, crossover and mutation functions --- genetic-algorithm.py | 20 ++++++++++++++++++++ 1 file changed, 20 insertions(+) diff --git a/genetic-algorithm.py b/genetic-algorithm.py index e69de29..8501840 100644 --- a/genetic-algorithm.py +++ b/genetic-algorithm.py @@ -0,0 +1,20 @@ +#/bin/python +import random + +tasks = [4, 5, 8, 2, 10, 7] +sol1=[1, 0, 1, 1, 0, 1] +sol2=[0, 0, 1, 0, 1, 1] + +def generate_initial_population(problem_data, k, popsize): + return [[random.randint(0, k-1) for _ in range(len(problem_data))] for _ in range(popsize)] + +def fitness(solution, problem_data, k): + return max([sum(problem_data[i] for i in range(len(solution)) if solution[i] == j) for j in range(k)]) + +def crossover(solutionA, solutionB): + return [solutionA[i] if i % 2 == 0 else solutionB[i] for i in range(len(solutionA))] + +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