Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import random
- # Перелік команд
- teams = ['Team 1', 'Team 2', 'Team 3', 'Team 4', 'Team 5', 'Team 6']
- # Кількість днів на відпочинок між матчами
- rest_days = 2
- # Кількість поколінь генетичного алгоритму
- generations = 100
- # Кількість особин у популяції
- population_size = 100
- # Ймовірність мутації
- mutation_rate = 0.1
- # Функція для створення випадкової популяції розкладів
- def create_population():
- population = []
- for i in range(population_size):
- schedule = []
- for j in range(len(teams)):
- for k in range(j + 1, len(teams)):
- match = [teams[j], teams[k], random.randint(0, rest_days)]
- schedule.append(match)
- random.shuffle(schedule)
- population.append(schedule)
- return population
- # Функція для розрахунку фітнес-функції для розкладу
- def calculate_fitness(schedule):
- team_rest_days = {}
- for team in teams:
- team_rest_days[team] = 0
- for match in schedule:
- team_rest_days[match[0]] += match[2]
- team_rest_days[match[1]] += match[2]
- avg_rest_days = sum(team_rest_days.values()) / len(team_rest_days)
- fitness = 1 / (1 + abs(avg_rest_days - max(team_rest_days.values())))
- return fitness
- # Функція для селекції найкращих особин з популяції
- def selection(population):
- fitness_scores = [(schedule, calculate_fitness(schedule)) for schedule in population]
- fitness_scores.sort(key=lambda x: x[1], reverse=True)
- selected = [schedule for schedule, fitness in fitness_scores[:int(population_size / 2)]]
- return selected
- # Функція для розмноження двох розкладів
- def crossover(schedule1, schedule2):
- child = []
- for i in range(len(schedule1)):
- if random.random() < 0.5:
- child.append(schedule1[i])
- else:
- child.append(schedule2[i])
- return child
- # Функція для мутації розкладу
- def mutate(schedule):
- for i in range(len(schedule)):
- if random.random() < mutation_rate:
- schedule[i][2] = random.randint(0, rest_days)
- return schedule
- # Генетичний алгоритм для створення розкладу
- def genetic_algorithm():
- population = create_population() # create_population
- for i in range(generations):
- selected = selection(population) # select the best schedules of the population
- children = []
- for j in range(int(population_size/2)):
- parent1 = random.choice(selected)
- parent2 = random.choice(selected)
- child = crossover(parent1, parent2) # crossover
- child = mutate(child) # mutate
- children.append(child)
- population = selected + children
- fitness_scores = [(schedule, calculate_fitness(schedule)) for schedule in population] # calculate_fitness
- fitness_scores.sort(key=lambda x: x[1], reverse=True)
- best_schedule = fitness_scores[0][0]
- return best_schedule
- print(genetic_algorithm())
Advertisement
Add Comment
Please, Sign In to add comment