ultra-mastermind-implementa.../lib/ultra_mastermind_obj.py
2024-11-12 12:53:55 +01:00

111 lines
2.9 KiB
Python

# Librairie du projet en version orientée objet
import random
def min_i(array: list[int]) -> int:
min_val = array[0]
min_i = 0
for i in range(len(array)):
if array[i] < min_val:
min_val = array[i]
min_i = i
return min_i
def max_i(array: list[int]) -> int:
max_val = array[0]
max_i = 0
for i in range(len(array)):
if array[i] > max_val:
max_val = array[i]
max_i = i
return max_i
class Population:
"""
Classe qui représente notre population d'individuts
"""
def __init__(self, pm, ng, n, ts, tm):
self.individuals = [Individual() for _ in range(n)]
for individual in self.individuals:
individual.randomize(len(pm))
self.pm = pm
self.ng = ng
self.l = len(pm)
self.n = n
self.ts = ts
self.tm = tm
def select(self) -> None:
fitness_list = []
for individual in self.individuals:
fitness_list.append(individual.fitness(self.pm))
for i in range(int((1 - self.ts) * self.n)):
least = min_i(fitness_list)
fitness_list.pop(least)
self.individuals.pop(least)
def reproduct(self) -> None:
new = []
while len(self.individuals) + len(new) != self.n:
cut = random.randint(int(self.l / 3), int(2 * self.l / 3))
indivi_1 = self.individuals[random.randint(0, len(self.individuals) - 1)]
indivi_2 = self.individuals[random.randint(0, len(self.individuals) - 1)]
while indivi_1 == indivi_2:
indivi_2 = self.individuals[random.randint(0, len(self.individuals) - 1)]
new_chromozome = indivi_1.getChromozome()[:cut] + indivi_2.getChromozome()[cut:]
child = Individual()
child.setChromozome(new_chromozome)
new.append(child)
self.individuals += new
def mutate(self) -> None:
mutated = []
for i in range(int(self.tm * self.n)):
to_mutate = random.randint(0, self.n - 1)
while to_mutate in mutated:
to_mutate = random.randint(0, self.n - 1)
self.individuals[to_mutate].mutate()
mutated.append(to_mutate)
def print_best(self) -> None:
fitness_list = []
for individual in self.individuals:
fitness_list.append(individual.fitness(self.pm))
print(self.individuals[max_i(fitness_list)].getChromozome())
def run(self) -> None:
for i in range(self.ng):
self.select()
self.reproduct()
self.mutate()
self.print_best()
class Individual:
"""
Classe qui représente les individuts de la population (les solutions potentielles)
"""
def __init__(self):
self.chromozome = ""
def setChromozome(self, c: str) -> None:
self.chromozome = c
def getChromozome(self) -> str:
return self.chromozome
def randomize(self, l) -> None:
new = ""
for i in range(l):
new += chr(random.randint(0, 255))
self.chromozome = new
def fitness(self, pm) -> int:
sum = 0
for i in range(len(self.chromozome)):
sum += abs(ord(self.chromozome[i]) - ord(pm[i]))
return -sum
def mutate(self) -> None:
new = list(self.chromozome)
new[random.randint(0, len(new) - 1)] = chr(random.randint(0, 255))
self.chromozome = "".join(new)