From de1ce36aed510e00378b4136214d2c20b4f64fea Mon Sep 17 00:00:00 2001 From: jbiesek Date: Wed, 8 Jun 2022 21:16:30 +0200 Subject: [PATCH] Genetical algorithm --- genetical_algorithm.py | 60 +++++++++++++++++++++++++++++++++++++++++- 1 file changed, 59 insertions(+), 1 deletion(-) diff --git a/genetical_algorithm.py b/genetical_algorithm.py index 05fa68c..01d3c09 100644 --- a/genetical_algorithm.py +++ b/genetical_algorithm.py @@ -1,3 +1,8 @@ +import random +from copy import copy +import settings +import tree + def evaluate_values(fuel, water, feritizer, seeds, fields_with_plants, k): fields_to_sow = 0 @@ -60,4 +65,57 @@ def fitness(solution, fields_plants, k): else: ans = evaluate_values(fuel, water, feritizer, seeds, fields_plants, k) return ans - \ No newline at end of file + + +def solution(fields_with_plants, l): + solutions = [] + ranked_solutions = [] + for i in range(10000): + solution = [] + fuel = random.randint(0, 2000) + water = random.randint(0, 100) + feritizer = random.randint(0, 100) + seeds = random.randint(0, 100) + solution.append(fuel) + solution.append(water) + solution.append(feritizer) + solution.append(seeds) + solutions.append(solution) + for s in solutions: + ranked_solutions.append((fitness(s, fields_with_plants, l), s)) + ranked_solutions.sort() + ranked_solutions.reverse() + best_solutions = ranked_solutions[:100] + k = 1 + print("Gen 1 best solution: " + str(ranked_solutions[0])) + for q in range(4): + k += 1 + random_cross = random.randint(0, 3) + random_mutation_place = random.randint(0, 3) + random_mutation = random.randint(1, 5) + ranked_solutions = [] + solutions = [] + solutions.append(best_solutions[0][1]) + for i in range(100): + for j in range(100): + if i == j: + continue + random_mutation_chance = random.randint(1, 100) + solution = copy(best_solutions[i][1]) + solution[random_cross:4] = best_solutions[j][1][random_cross:4] + if random_mutation_chance <= 3: + if random_mutation_place == 0: + solution[random_mutation_place] = solution[random_mutation_place] + random_mutation * 30 + else: + solution[random_mutation_place] = solution[random_mutation_place] + random_mutation + solutions.append(copy(solution)) + + for s in solutions: + ranked_solutions.append((fitness(s, fields_with_plants, l), s)) + ranked_solutions.sort() + ranked_solutions.reverse() + + best_solutions = ranked_solutions[:100] + print("Gen " + str(k) + " best solution: " + str(ranked_solutions[0])) + + return ranked_solutions[0][1][0], ranked_solutions[0][1][1], ranked_solutions[0][1][2], ranked_solutions[0][1][3]