Genetical algorithm
This commit is contained in:
parent
87d29f24e0
commit
de1ce36aed
@ -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
|
||||
@ -61,3 +66,56 @@ def fitness(solution, fields_plants, k):
|
||||
ans = evaluate_values(fuel, water, feritizer, seeds, fields_plants, k)
|
||||
return ans
|
||||
|
||||
|
||||
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]
|
||||
|
Loading…
Reference in New Issue
Block a user